Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
91247
|programming|sketch|loop|
How to write a program to do 2 different loop | Task?
2022-11-06T22:41:34.873
<p>I wanna write a program for rc-plane navigation</p> <p>The plane must navigate to 2 waypoints waypoint_1 &amp; waypoint_2 When it reaches to waypoint_1 (with miss-distance =&lt; 5) then navigate to waypoint_2</p> <p>But i have a problem.</p> <p>First look at this :</p> <pre><code>void loop(){ if (distance-to-waypoint_1 &gt; 5 meters) { Navigate to waypoint_1 if distace-to-waypoint_1 &lt; 5 meters : Navigate-to-waypoint_2 </code></pre> <p>If i use a code like this, plane will navigate to waypoint_1 and when it reaches somewhere that has less than 5 meters distance to waypoint_1, then will navigate to waypoint_2, but if plane fly away and the distance between it's location and waypoint_1 goes greater than 5 meters, plane return to previous navigation and will navigate to waypoint_1 again and ignore navigation to waypoint_2</p> <p>So, i need a form of programme to first do a loop for navigation to navigate the plane to waypoint_1 and when it reaches the waypoint_1 , do another loop to navigate the plane to waypoint_2</p> <p>Thanks</p>
<p>I think you should use a different logic by using a variable to hold the current target waypoint and separate the code to reach a waypoint and to change it.</p> <p>Something like this (in pseudocode):</p> <pre><code>declare variable target_waypoint and set it to waypoint1 loop Fly towards target waypoint if distance to target waypoint lower than 5 change target_waypoint to waypoint 2 </code></pre> <p>You can easily extent that for more waypoints by using an array of waypoints and a variable holding the index of the next waypoint:</p> <pre><code>declare waypoints as array declare index variable, initialize with zero set target_waypoint to waypoints[index] loop Fly towards target waypoint if distance to target waypoint lower than 5 increment index if index greater than max index Either set to zero to loop through all waypoints again or do whatever you want to do after the waypoints set target_waypoint to waypoints[index] </code></pre> <p>The code that moves you to the waypoint doesn't care about what waypoint is next. It's only doing this one job. And when you reached a waypoint you simply move the target of that code to a different position.</p> <p>Much like you yourself would walk between different waypoints. Setting first waypoint as target, walking towards it until you reached it, setting the next waypoint as target and doing the walking again.</p>
91260
|arduino-mega|sensors|arduino-micro|raspberrypi|
How to architect streaming data from multiple plant monitors to single Arduino?
2022-11-08T01:03:29.647
<h2>Premise:</h2> <p>I'm trying to determine a good way to architect getting data from 4 plant monitors to a single Arduino. For context, that Arduino will have a Wifi connection that will transmit the data from the plant monitors to a web server internally.</p> <h2>Setup</h2> <p>Where I'm struggling to make a decision is how to go about hooking the sensors up. Here's my plant setup:</p> <p><img src="https://i.stack.imgur.com/FIweI.jpg" alt="Three tiered plant shelves with 11 plants." /></p> <h2>Materials</h2> <p>Tools I have at hand:</p> <ul> <li>Many Arudino Micros</li> <li>Arduino Unos</li> <li>Arduino Mega</li> <li>Raspberry Pi 4 B</li> <li>4x <a href="https://monkmakes.com/pmon" rel="nofollow noreferrer">Monk Makes Plant Monitors</a></li> <li>Wiring stuff and power supplies, basic electronics prototyping collection.</li> </ul> <h2>Solutions?</h2> <p>I would like to place 4 monitors into different plants (doesn't matter which ones at the moment, if it does, I can specify). What I've considered:</p> <ol> <li>All 4 plant monitors directly wired to the Arduino Mega. This requires a 1k resistor in line of the data pin, which I'm not sure I have a good solution for that without a breadboard. Also, I wasn't sure if the length of data line would be a problem.</li> <li>Each Plant Monitor is hooked up to an Arduino micro and then use the USB of the micro to the RPI.</li> <li>Like #2 but use I2C to send data to Arduino Mega. I would need to supply power to these minis then.</li> <li>There are some options without using Arduinos, but since is the Arduino SE, I'm happy to keep it with this.</li> </ol> <p>I'm open to other options as well, as well as possibly needing to purchase/make another part to optimize the solution some.</p>
<p>The distances between the plants on the shelf are in general too long for TTL level communication and soon you may want to connect more sensors at plants elsewhere in the room or even in other rooms.</p> <p>In my opinion the solution proposed by dandavis, using esp-01 with WiFi or esp-now is the most simple and universal solution. I see no problems with the implementation. The esp-01 is small and will play nice with the 3.3 V sensor. Maybe it can be even made battery powered and then there are no cables between plants.</p> <p>If wired solution was required, I would recommend to use RS485 bus. With RS485 modules with AutoDirection control the sensors could be directly connected to the RS485 module without a MCU at every sensor.</p>
91273
|arduino-uno|pwm|ethernet|analogwrite|digitalwrite|
How to control PWM and digital pins at the same time over ethernet in arduino
2022-11-09T13:19:08.803
<p>I am using <a href="https://www.controllino.com/product/controllino-maxi/" rel="nofollow noreferrer">Controllino Maxi</a>. It has an Arduino Uno inside it. I am trying to control the PWM pin <code>D0</code> and digital pin <code>R0</code> via <code>python</code> code. Below is the code I have upload on arduino:</p> <p><code>Arduino Code</code>:</p> <pre><code>#include &lt;Ethernet.h&gt; #include &lt;EthernetUdp.h&gt; #include &lt;SPI.h&gt; #include &lt;Controllino.h&gt; byte mac[] ={}; IPAddress ip(192, 168, 0, 200); unsigned int localPort = 5000; char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; String datReq; int packetSize; EthernetUDP Udp; void setup() { Ethernet.begin( mac, ip); Udp.begin(localPort); //Initialize Udp pinMode(CONTROLLINO_D0, OUTPUT); pinMode(CONTROLLINO_R0, OUTPUT); } void loop() { packetSize =Udp.parsePacket(); //Reads the packet size if(packetSize&gt;0) { Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request String datReq(packetBuffer); if (datReq == &quot;R0&quot;) { digitalWrite(CONTROLLINO_R0, HIGH); delay(2000); digitalWrite(CONTROLLINO_R0, LOW); } else { analogWrite(CONTROLLINO_D0, datReq.toInt()); delay(2000); analogWrite(CONTROLLINO_D0, 0); } } } </code></pre> <p>In above code, if I receive <code>R0</code> over ethernet, then I am turning on/off <code>R0</code> pin, else whatever PWM I am receiving, I am setting it using <code>analogWrite</code>. Below is my <code>python</code> code:</p> <pre><code>from socket import * import time address = ('192.168.0.200', 5000) # define server IP and port ((0x12, 0x02, 0x00, 0x00, 0xEA, 0x03)) client_socket = socket(AF_INET, SOCK_DGRAM) # Set up the Socket client_socket.settimeout(1) data = &quot;R0&quot;.encode(&quot;utf-8&quot;) client_socket.sendto(data, address) time.sleep(5) data = (&quot;{}&quot;.format(200)).encode(&quot;utf-8&quot;) client_socket.sendto(data, address) time.sleep(5) data = (&quot;{}&quot;.format(&quot;R0&quot;)).encode(&quot;utf-8&quot;) client_socket.sendto(data, address) </code></pre> <p>In above code, I am first sending <code>R0</code> to turn on/off <code>R0</code> and then sending <code>200</code> for PWM and then again sending <code>R0</code> to turn on/off <code>R0</code>. When tested I can see <code>R0</code> getting high and low, then I can see <code>200</code> on PWM but then again <code>R0</code> should be high/low but it stays low. If I re run the python code, <code>R0</code> doesnt work and only PWM works. If I power off the board and power it again, then <code>R0</code> works only for first time and it didnt work in second time.</p> <p>I am a bit confused at this stage. Is there any bug in my arduino code as I am not very experienced in it. Is there any way to debug it? Please help. THanks</p>
<p>You Arduino sketch is storing the received UDP packet in a <code>char</code> array named <code>packetBuffer</code>, then converting this array to a <code>String</code> object like this:</p> <pre class="lang-cpp prettyprint-override"><code>String datReq(packetBuffer); </code></pre> <p>The problem is that this <code>String</code> constructor expects a NUL-terminated array, and you have no guarantee that this array is NUL-terminated.</p> <p>Well, actually you have this guarantee, but only at the beginning: as the program starts, the array will be filled with zeros by the C initialization routine. This is why the first request is correctly processed. The second request sends a packet larger than the first one, so the array is still NUL-terminated. On the third request, however, the received bytes are immediately followed by the leftovers of the previous request. In this case it is the digit <code>'0'</code>.</p> <p>The simple solution is to ensure that the buffer is always properly terminated. Start by making it wider by one byte:</p> <pre class="lang-cpp prettyprint-override"><code>char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // +1 for the '\0' </code></pre> <p>Then, whenever you receive a packet, add the terminating NUL character:</p> <pre class="lang-cpp prettyprint-override"><code>Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request packetBuffer[packetSize] = '\0'; // properly terminate the buffer </code></pre>
91277
|pwm|analogwrite|
What should happen when sending analogWrite signal to a non-PWM pin?
2022-11-10T00:56:13.730
<p>I'm a very new to Arduino and any electrical engineering, I'm learning through some Youtube tutorials.</p> <p>Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.</p> <p><strong>BUT</strong> ... that's not what I'm seeing in practice...</p> <p>Using Arduino UNO, I made a little project, for changing a blue LED's brightness. At first I did it through a PWM pin (pin 9) and it worked flawlessly. But then I tried seeing what would happen in a non-PWM pin (pin 8), you know cause you learn by trying and experimenting. So I switched to a non-PWM pin and ... it works the same exact way ...</p> <p>I can change the brightness of the LED <strong>5 different levels</strong> ... using analogWrite ... to a non-PWM pin ...</p> <p>Thanks in advance</p>
<blockquote> <p>Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.</p> </blockquote> <p>On the Uno you do not send analog signals anywhere. The PWM pins are merely digital outputs which turn on and off rapidly at a frequency and duty cycle that you specify.</p> <p>You can, therefore, do the same thing to non-PWM pins by sending HIGH/LOW at a variable rate.</p> <p>To comment more on why your code appears to be &quot;working&quot; we would need to see it.</p> <hr /> <blockquote> <p>What is the point of PWM pins if its also possible to send variable high/low signals to non-PWM pins?</p> </blockquote> <p>Well, the PWM pins output high/low signals asynchronously. That is, without code having to do it. So, if you set up a timer (which is connected to the PWM pins) to output 100kHz then it will do that, regardless of what the code is doing at the time. You might be calculating prime numbers, but the hardware timers will mindlessly toggle that PWM pin on and off at the specified frequency.</p> <p>If you try to make your own PWM in code, then the code has to do that <strong>and nothing else</strong> if it is going to output a consistent signal.</p>
91282
|char|
char * variable - Handle correctly to avoid overflow
2022-11-11T07:06:00.863
<p>I'm trying to understand if a <code>char *</code> variable can be updated down the code (since it only stores a pointer) or over-flow can occur.</p> <p>For example:</p> <p><code>char *A=&quot;/file.txt&quot;;</code></p> <p><code>char *B;</code></p> <pre><code>void print_filename(char *filename=&quot;/defname.txt&quot;){ Serial.println(filename); </code></pre> <p>Is is the right way to use <code>char*</code> variable, so down the road I assing new values :</p> <p><code>A=&quot;/anyOtherfile.txt&quot;;</code></p> <p><code>B=&quot;This_is_not_empty&quot;;</code></p> <p><code>print_filename(&quot;/logfile.txt&quot;);</code></p>
<p>No overflow can occur when using <code>char</code> pointers like you did in your question.</p> <p>You use a number of different string literals (the strings enclosed by double quotes). These automatically get placed in RAM by the compiler, but they are not meant to be writable. When you do</p> <pre><code>char *A=&quot;/file.txt&quot;; </code></pre> <p>the compiler will place the literal in RAM (not in stack, but in the read-only section, even if the literal is used inside of a function (Thanks to Edgar Bonet for the comment)) and then set the pointer <code>A</code> to the address of that literal. Writing to that address is undefined in the C++ standard and should not be done.</p> <p>When you then do something like this</p> <pre><code>A = &quot;some other literal&quot;; </code></pre> <p>then you are not changing the literal. Instead you are just changing the pointer to a different literal placed in RAM. So no overflow can occur, since the compiler just takes all string literals, places them in RAM (immutable) and only handles their memory addresses. So there is no writable buffer in the first place.</p> <p>With</p> <pre><code>void print_filename(char *filename=&quot;/defname.txt&quot;){ Serial.println(filename); </code></pre> <p>you are setting the default value of the <code>filename</code> pointer to the address of that specific literal. Setting the parameter to an address of another literal or an existing <code>char</code> array will just change the pointer. If you at another pointer again set <code>filename</code>to that exact literal, the literal still lies in RAM and the compiler will usage again its address (so multiple uses of the same literal will not result in higher memory use).</p> <p>If you - at some point - want to write data to that pointer, you first need to set it to a <code>char</code> array, either the address of a static array or creating a new dynamically allocated array with the <code>new</code> keyword:</p> <pre><code>char my_static_array[10]; A = my_static_array; // now you can write to the array my_static_array by using A A = new char[15]; // now you can write to a newly created array by using A </code></pre> <p>Though for the dynamic allocation you need to keep in mind, that especially AVR based Arduinos (like the Uno/Nano/Mini) don't have much memory and often dynamically declaring and deleting memory can lead to memory fragmentation (essentially the delete operations free memory, but these holes with free memory are often too small for the next allocations, so they don't get used and your memory gets like swiss cheese). That is also the reason why using the Arduino <code>String</code> class in the wrong way is really bad.</p>
91286
|arduino-ide|string|loop|
for loop crashes program
2022-11-11T08:59:40.977
<p>Just started out with tinyduino(tinycircuits) and I am trying to develop a hangman game. I have this chunk of code that randomly picks a word from my array. I've omitted some code for readability.</p> <pre><code>char* words[] = {&quot;Fortran&quot;, &quot;Cobol&quot;, &quot;Python&quot;, &quot;Java&quot;, &quot;Javascript&quot;, &quot;Kotlin&quot;, &quot;Swift&quot;, &quot;Golang&quot;, &quot;Typescript&quot;}; long word1; char* generatedWord1; int k; int i; int wordLength; void setup(void) { randomSeed(analogRead(5)); hangman(); void hangman(){ word1 = random(sizeof(words)/sizeof(char*)); k = 1; if (k == 1) { display.setCursor(10, 50); generatedWord1 = words[word1]; for (i = 0; generatedWord1[i]; i++) { generatedWord1[i] = &quot;_&quot;; } } </code></pre> <p>When I upload this to my board, it would not display the underscores based on the randomly chosen word's length. Re-uploading it does not work and usually requires me to reboot the tinyduino after that. Hence, I concluded my code crashes it. But, when I replace the <code>generatedWord1[i] = &quot;_&quot;;</code> in the <code>for loop</code> with <code>display.print(&quot;_&quot;);</code> the program carries on and it prints the correct amount of underscores.</p> <p>However, this does not fit my purpose of replacing the letters with underscores, as <code>display.print(&quot;_&quot;);</code> just prints underscores based on the random word's length instead. I need it to be in a manner where I can still compare a user input against the random word and replace the underscore if the letter input matches any letters in the word.</p> <p>What and how do I modify my code to work as such?</p> <p>Note: For the context of this whole sketch, I am trying to use get an input from a user through bluetooth and compare whether or not the input matches any of the letters from the random word and then replace the underscore with the input letter. Completing the word means winning the game as per hangman.</p> <p><strong>EDIT</strong>: I've added the whole sketch below for reference just in case I missed out something important for my question.</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;STBLE.h&gt; #include &lt;Wire.h&gt; #include &lt;SPI.h&gt; #include &lt;TinyScreen.h&gt; #include &lt;string.h&gt; //Debug output adds extra flash and memory requirements! #ifndef BLE_DEBUG #define BLE_DEBUG true #endif #if defined (ARDUINO_ARCH_AVR) #define SerialMonitorInterface Serial #elif defined(ARDUINO_ARCH_SAMD) #define SerialMonitorInterface SerialUSB #endif uint8_t ble_rx_buffer[21]; uint8_t ble_rx_buffer_len = 0; uint8_t ble_connection_state = false; #define PIPE_UART_OVER_BTLE_UART_TX_TX 0 TinyScreen display = TinyScreen(TinyScreenDefault); // declarations const char* words[] = {&quot;Fortran&quot;, &quot;Cobol&quot;, &quot;Python&quot;, &quot;Java&quot;, &quot;Javascript&quot;, &quot;Kotlin&quot;, &quot;Swift&quot;, &quot;Golang&quot;, &quot;Typescript&quot;}; long word1; const char* generatedWord1; int k; int i; int length; void setup(void) { Serial.begin(9600); randomSeed(analogRead(5)); BLEsetup(); Wire.begin(); display.begin(); display.setBrightness(10); hangman(); } void hangman(){ display.clearScreen(); display.setFont(thinPixel7_10ptFontInfo); display.setCursor(10,20); display.print(&quot;Ready to hang?&quot;); delay(2000); display.setCursor(5,20); display.print(&quot;generating word...&quot;); delay(1000); display.clearScreen(); // word1 is my index, so printing out word1 will give you a random index from the array word1 = random(sizeof(words)/sizeof(char*)); k = 1; if (k == 1) { display.setCursor(10, 50); generatedWord1 = words[word1]; length = strlen(generatedWord1); char user_input[length+1] = &quot;&quot;; for (i=0; i &lt; length; i++) { user_input[i] = &quot;&quot;; user_input[length] = 0; } display.setCursor(30, 30); display.print(&quot;|&quot;); display.setCursor(30, 20); display.print(&quot;|&quot;); display.setCursor(30, 10); display.print(&quot;|&quot;); display.setCursor(30, 0); display.print(&quot;____&quot;); // remember to move this away from the if statement // If user guesses wrong letter (1) display.setCursor(50, 10); display.print(&quot;|&quot;); // If user guesses wrong letter (2) display.setCursor(49, 15); display.print(&quot;o&quot;); // If user guesses wrong letter (3) display.setCursor(50, 25); display.print(&quot;|&quot;); // If user guesses wrong letter (4) display.setCursor(43, 21); display.print(&quot;-&quot;); // If user guesses wrong letter (5) display.setCursor(54, 21); display.print(&quot;-&quot;); // IF user guesses wrong letter (6) display.setCursor(43, 30); display.print(&quot;/&quot;); // If user guesses wrong letter (7) display.setCursor(52, 30); display.print(&quot;\\&quot;); } } void displayScreen(char phone_input[21]) { display.clearScreen(); int width=display.getPrintWidth(phone_input); display.setFont(thinPixel7_10ptFontInfo); display.setCursor(48-(width/2),32); display.fontColor(TS_8b_White,TS_8b_Black); display.print(phone_input); } void loop() { aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short. if (ble_rx_buffer_len) {//Check if data is available delay(10); displayScreen((char*)ble_rx_buffer); ble_rx_buffer_len = 0;//clear afer reading } } </code></pre>
<p>Funny, I just wrote an <a href="https://arduino.stackexchange.com/questions/91282/char-variable-handle-correctly-to-avoid-overflow">answer</a> about the problem, that you have here, about 45min ago. And the problem is, that you are trying to modify a string literal. That is undefined behavior in C++.</p> <p>When you declare your words array with</p> <pre><code>char* words[] = {&quot;Fortran&quot;, &quot;Cobol&quot;, &quot;Python&quot;, &quot;Java&quot;, &quot;Javascript&quot;, &quot;Kotlin&quot;, &quot;Swift&quot;, &quot;Golang&quot;, &quot;Typescript&quot;}; </code></pre> <p>you are actually defining an array of pointers. The compiler will place these strings in the RAM and place their memory addresses in the array. Then you are declaring another <code>char</code> pointer and set it to one of the words:</p> <pre><code>char* generatedWord1; generatedWord1 = words[word1]; </code></pre> <p>So now <code>generatedWord1</code> will also point to one of the string literals. And then you are trying to write to this string literal:</p> <pre><code>generatedWord1[i] = &quot;_&quot;; </code></pre> <p>But - as already mentioned - string literals are not meant to be changed. Trying so is undefined behavior and yes, it can lead crashes.</p> <p><strong>What to do now?</strong> You can define an array of <code>char</code> (not <code>char</code> pointers) as a buffer and fill it with the number of underscores that equals the length of the string literal. When defining the array you can choose the length of the string literal (plus 1 to accommodate the null character) as size, though - depending on your program flow, that you didn't show - it might be better to just declare a buffer with a fixed size bigger than the longest of your words.</p> <p>You can get the length of the string literal with the <code>strlen()</code> function:</p> <pre><code>int length = strlen(generatedWord1); </code></pre> <p>Defining the <code>char</code> buffer:</p> <pre><code>char user_input[length+1] = &quot;&quot;; </code></pre> <p>Filling it with underscores</p> <pre><code>for(int i=0;i&lt;length;i++){ user_input[i] = '_'; } user_input[length] = 0; // terminating null character </code></pre> <blockquote> <p>I still can't get the desired output I would like. Also it keeps throwing me an error of invalid conversion from 'const char*' to 'char'.</p> </blockquote> <p>The following part is wrong:</p> <pre><code>for (i=0; i &lt; length; i++) { user_input[i] = &quot;&quot;; user_input[length] = 0; } </code></pre> <p>First: You misunderstood what is in the loop and what not. I changed my snipped above to use curly braces. Terminating the string with the null character can be done outside of the loop.</p> <p>Second: You wanted to fill the buffer with underscores. If you look at my code snippet I assigned an underscore here.</p> <p>The warning that you are getting from the compiler also lies in this line. You have used double quotes. Those mark a string literal. But here we are assigning a single character, so you need to use single quotes, which mark single characters.</p> <p>The message <code>invalid conversion from const char* to char</code> means, that you used a string literal (which is a pointer to a constant character) and assigned it to a single character variable (one element of the <code>char</code> array).</p>
91295
|esp8266|string|
generate x item long list for gyverportal drop-down selection
2022-11-12T18:35:23.377
<p>I am trying to make a drop down selection with gyverportal. The issue is that I don't know how many items there are so the list cannot be hard coded. Here is an example from github:</p> <pre><code>GP.SELECT(&quot;sel&quot;, &quot;val 1,val 2,val 3&quot;, valSelect); //where sel is the name of the field and valselect is the currently selected item. </code></pre> <p>I am very confused with the different types of text (char, char*, const char, const char*, String, char array[10]...just to name a few) and the operations with them seem a nightmare. I think gyverportal expects a &quot;char*&quot; for the list.</p> <p>for context: The items are loaded from EEPROM and the number is stored in Length.</p> <p>what I need is:</p> <p>for 0 items: &quot;none&quot;</p> <p>for 5 items: &quot;1,2,3,4,5,none&quot;</p> <p>for 10 items: &quot;1,2,3,4,5,6,7,8,9,10,none&quot;</p> <pre><code>int Length=5; //I have five items to select from char* dropdownoptions= &quot;&quot;; if (Length&lt;1){ dropdownoptions=&quot;none&quot;; }else{ char Answ[60]=&quot;1,&quot;; for (int i=1; i&lt;=Length; i++){ char part[3]; String str=String(i+1); str.toCharArray(part, 3); strcat(Answ,part); strcat(Answ,&quot;,&quot;); } strcpy(dropdownoptions,Answ); strcat(dropdownoptions,&quot;none&quot;); } Serial.println (dropdownoptions); </code></pre> <p>This code has been rewritten like 30 times and compiles, but crashes the board (esp8266) aka boot-looping</p> <p>Ideally this is what I would like to do</p> <pre><code>dropdownoptions= &quot;&quot;; for (int i=1; i&lt;=Length; i++){ dropdownoptions+=i; dropdownoptions+=&quot;,&quot;; } dropdownoptions+=&quot;none&quot;; </code></pre>
<p>As explained by chrisl in his answer, you have to declare <code>dropdownoptions</code> as an array of <code>char</code> large enough to hold the whole string, including the terminating <code>'\0'</code>. If you know beforehand the maximum value of <code>Length</code>, you could size the array accordingly. Otherwise, you may compute the required size as a function of <code>Length</code>:</p> <pre class="lang-cpp prettyprint-override"><code>int str_length; // size of the string, including the final '\0' if (Length &lt; 10) str_length = 2 * Length + 5; else str_length = 3 * Length - 4; // assume Length &lt; 100 char dropdownoptions[str_length]; </code></pre> <p>Then you have to write the contents into this array. One way to do it would be to write each individual piece into a temporary array, then copy it to the array <code>dropdownoptions</code> by using string concatenation. My preferred way of filling the array, however, is the “zero-copy” method consisting of writing the pieces straight into the right place of the final array. This requires some pointer manipulation. If you are too uncomfortable with pointers, you may skip this answer. But if you want to learn and get some practice, please read on.</p> <p>Let <code>p</code> be a pointer to the current array position where you want to write. You can pass this pointer to <a href="https://cplusplus.com/reference/cstdio/sprintf/" rel="nofollow noreferrer"><code>sprintf()</code></a> in order to write a piece of data into the buffer at the right place. <code>sprintf()</code> returns the number of bytes written, not counting the terminating <code>'\0'</code>, and you can then advance the pointer <code>p</code> by this exact amount in order to know where to write the next piece. In code:</p> <pre class="lang-cpp prettyprint-override"><code>char *p = dropdownoptions; // current write position for (int i = 1; i &lt;= Length; i++) { p += sprintf(p, &quot;%d,&quot;, i); } sprintf(p, &quot;none&quot;); </code></pre> <p>There is one drawback to using <code>sprintf()</code> though: if you get the size of the array wrong and too short, you will end up writing past its end and corrupting your memory. If you want to be defensive, you should keep track of the amount of available space remaining, and use the function <a href="https://cplusplus.com/reference/cstdio/snprintf/" rel="nofollow noreferrer"><code>snprintf()</code></a> instead. This function takes, as a second parameter, the number of bytes available in the buffer, and it will never overflow that buffer. I find that the easiest way of keeping track of the remaining space is to initialize a pointer to the end of the array (technically, “one past the end” of the array), and compute the available space as <code>end-p</code>:</p> <pre class="lang-cpp prettyprint-override"><code>char *p = dropdownoptions; // current write position const char *end = dropdownoptions + str_length; // end of the array for (int i = 1; i &lt;= Length; i++) { int count = snprintf(p, end - p, &quot;%d,&quot;, i); p += min(count, end - p); } snprintf(p, end - p, &quot;none&quot;); </code></pre> <p>The reason of <code>min()</code> being used here is that <code>snprintf()</code> may return a number larger than the available space: if the buffer is too small, this function returns the number of characters that <em>would had been written</em> (not counting the terminating <code>'\0'</code>) had the buffer been large enough.</p>
91306
|arduino-ide|attiny|avr|avrdude|
Issues Uploading Code to ATTiny84 with Sparkfun AVR Pocket Programmer and ATTinyCore
2022-11-14T01:11:32.180
<p>I am getting back into programming with Arduino and built a POV fidget spinner inspired by an instructable by MakersBox. I am using the SparkFun AVR Pocket Programmer and an ATTiny84 (8MHz internal clock) with ATTinyCore as the board manager.</p> <p>I was able to upload the code without error a few days ago using the 'USBTinyISP (ATTinyCore) FAST, for parts running &gt;= 2MHz' programmer selection but it stopped working. Now the below error shows:</p> <pre><code>avrdude: Version 6.3-20201216 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is &quot;C:\Users\Franklin Marquette\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.5.2/avrdude.conf&quot; Using Port : usb Using Programmer : usbtiny Setting bit clk period : 0.3 avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x1781-0x0c9f AVR Part : ATtiny84 Chip Erase delay : 15000 us PAGEL : P00 BS2 : P00 RESET disposition : possible i/o 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 6 4 0 no 512 4 0 4000 4500 0xff 0xff flash 65 6 32 0 yes 8192 64 128 4500 4500 0xff 0xff signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 lock 0 0 0 0 no 1 0 0 9000 9000 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 calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 Programmer Type : USBtiny Description : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/ avrdude: programmer operation not supported avrdude: Setting SCK period to 1 usec avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check. avrdude done. Thank you. Failed programming: uploading error: exit status 1 </code></pre> <p><strong>NOW</strong> if I upload using the &quot;USBtinyISP (ATtinyCore) SLOW, for new or 1 MHz parts&quot; programmer option, the code does upload. It is 8x slower though. I uploaded the Blink sketch to a separate ATTiny84 on a breadboard and the connected LED stayed on for ~7.75s when it was programmed to stay on for 1s.</p> <p>I have no idea what is going on and would really appreciate any help that I can get. <strong>Thank you!</strong></p> <p>For reference, the code is below.</p> <pre><code>/* Not all Attiny cores support the tone() function. Try this one https://github.com/SpenceKonde/ATTinyCore // ATMEL ATTINY84 / ARDUINO // // +-\/-+ // VCC 1| |14 GND // (D 0) PB0 2| |13 AREF (D 10) // (D 1) PB1 3| |12 PA1 (D 9) // PB3 4| |11 PA2 (D 8) // PWM INT0 (D 2) PB2 5| |10 PA3 (D 7) // PWM (D 3) PA7 6| |9 PA4 (D 6) // PWM (D 4) PA6 7| |8 PA5 (D 5) PWM */ #include &lt;EEPROMex.h&gt; #include &lt;avr/pgmspace.h&gt; #include &quot;font.h&quot; #include &quot;textAndShapes.h&quot; const int charHeight = 8; const int charWidth = 5; int rows= 8; // Total LED's in a row int LEDS[] = {0, 1, 2, 3, 4, 5, 7, 6}; bool STATES[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW}; char charArray[6]; // holds characters to display unsigned long lastTimeUs; // time (us) magnet sensed unsigned long revTimeUs; // time (us) of last full rotation unsigned long dwellTimeUs; // time (us) between LED changes (based on rotation speed) volatile unsigned long revolutions = 0; // track number of revolutions since last start long totalRevolutions; // track total number of revolutions (stored in EEPROM) bool spinning = true; // track reset of time &amp; counts unsigned long startTimeUs; // time (us) current spinning started int mode; // current operating mode, stored in EEPROM int modes = 8; // number of modes available // 0 -&gt; text &quot;Hello World!&quot; // 1 -&gt; RPM // 2 -&gt; time in seconds // 3 -&gt; spin count // 4 -&gt; spin count (total) // 5 -&gt; &quot;lilly pad&quot; pattern // 6 -&gt; shape 1 (heart) // 7 -&gt; shape 2 (smile) byte ledPin = 0; byte magPin = 0; // Hall effect sensor, pulled-up, goes low when magnet passes byte magPullUp = 10; // Pin A0 / D10 byte touchPin = 1; // Push button A1 / D9 byte touchPullUp = 9; volatile boolean rotationFlag = false; // modified by ISR void setup(){ // setup inputs pinMode(touchPin, INPUT); digitalWrite(touchPullUp, HIGH); pinMode(magPin, INPUT); digitalWrite(magPullUp, HIGH); // setup other LEDs for(int LED=0; LED&lt;(sizeof(LEDS)/sizeof(int)); LED++){ pinMode(LEDS[LED], OUTPUT); digitalWrite(LEDS[LED], STATES[LED]); } // Interupt setting GIMSK = bit (PCIE0); // Pin change interrupt enable PCMSK0 = bit (PCINT0); // Enable interupt on PCINT0 (D10) sei(); // enables interrupts // get saved mode from eeprom mode = EEPROM.read(0); if (mode &gt;= modes) { mode = 0; // may be very large first time } // get saved revolution total from eeprom totalRevolutions = EEPROMReadlong(1); if (totalRevolutions &lt; 0 || totalRevolutions &gt; 999999UL){ // will be -1 first time. totalRevolutions = 0; EEPROMWritelong(1, 0); } // show we are alive and what mode is active blipLEDs(); lastTimeUs = micros(); } void loop(){ int sigFigs = 6; // number of significant figures to deplay unsigned long curTimeUs; int seconds; unsigned int rpm; checkButton(); if (((micros() - lastTimeUs) &gt; 1000000UL)){ // less than 1 rev / sec if (spinning){ spinning = false; totalRevolutions = totalRevolutions + revolutions; EEPROMWritelong(1, totalRevolutions); revolutions = 0; clearArray(); blipLEDs(); } else { //digitalWrite(LEDS[mode], LOW); } } if (mode == 5){ // lilly pad pattern, show regardles of magnet. for(int LED=0; LED&lt;(sizeof(LEDS)/sizeof(int)); LED++){ digitalWrite(LEDS[LED], HIGH); delay(1); digitalWrite(LEDS[LED], LOW); } for(int LED=(sizeof(LEDS)/sizeof(int))-1; LED &gt;= 0; LED--){ digitalWrite(LEDS[LED], HIGH); delay(1); digitalWrite(LEDS[LED], LOW); } } else if (rotationFlag){ // we are spinning! rotationFlag = false; if (!spinning){ spinning = true; startTimeUs = micros(); } curTimeUs = micros(); revTimeUs = curTimeUs - lastTimeUs; dwellTimeUs = revTimeUs * 3UL / 360UL; // 3 degrees seconds = (curTimeUs - startTimeUs) / 1000000UL; rpm = 60000 * 1000 / revTimeUs; lastTimeUs = curTimeUs; clearArray(); if (mode == 0){ strcpy (charArray, text); //sprintf(charArray, &quot;%lu&quot;, dwellTimeUs); } else if (mode == 1){ sprintf(charArray, &quot;%d&quot;, rpm); sigFigs = 2; } else if (mode == 2){ sprintf(charArray, &quot;%d&quot;, seconds); } else if (mode == 3){ sprintf(charArray, &quot;%lu&quot;, revolutions); } else if (mode == 4){ sprintf(charArray, &quot;%lu&quot;, totalRevolutions + revolutions); } else if (mode == 6){ // shape 1 (heart) for(int k=0; k&lt; sizeof(shape_1);k++){ if (rotationFlag){ break; } char b = pgm_read_byte_near(&amp;(shape_1[k])); for (int j=0; j&lt;charHeight; j++) { digitalWrite(LEDS[j], bitRead(b, 7-j)); } dwellTimeUs = revTimeUs * 4UL / 360UL; // 5 degrees delayMicroseconds(dwellTimeUs); } } else if (mode == 7){ // shape 2 (smile) for(int k=0; k&lt; sizeof(shape_2);k++){ if (rotationFlag){ break; } char b = pgm_read_byte_near(&amp;(shape_2[k])); for (int j=0; j&lt;charHeight; j++) { digitalWrite(LEDS[j], bitRead(b, 7-j)); } dwellTimeUs = revTimeUs * 4UL / 360UL; // 5 degrees delayMicroseconds(dwellTimeUs); } } // Text in top half if (mode &lt; 5) { int digits = 0; for(int k=0; k&lt; sizeof(charArray);k++){ char c = charArray[k]; if (rotationFlag){ break; } if(c){ if (digits &lt; sigFigs){ printLetter(c); //digits += 1; } else{ printLetter('0'); } digits += 1; } } // Handle display in lower section clearArray(); if(1 &amp;&amp; (revTimeUs &lt; 200000)){ char * ptr = (char *) pgm_read_word (&amp;string_table[mode]); //char buffer [6]; // must be large enough! strcpy_P (charArray, ptr); // wait for it . . . while((micros() &lt; (lastTimeUs + revTimeUs / 2)) &amp;&amp; !rotationFlag){}; // show it for (int k=sizeof(charArray)-1; k&gt;=0; k--){ if (rotationFlag){ break; } printLetterLower(charArray[k]);; } } } } } ISR(PCINT0_vect){ // Magnet sensed if (!digitalRead(magPullUp)){ rotationFlag = true; // Increment volatile variables revolutions += 1; } } void dwellDelay(){ // avoid glitch on first rotation having erronious value if (dwellTimeUs &gt; 2000){ dwellTimeUs = 2000; } if (dwellTimeUs &lt; 100){ dwellTimeUs = 100; } delayMicroseconds(dwellTimeUs); } void printLetter(char ch){ // https://github.com/reger-men/Arduion-POV-clock/blob/master/clock.ino // make sure the character is within the alphabet bounds (defined by the font.h file) // if it's not, make it a blank character if (ch &lt; 32 || ch &gt; 126){ ch = 32; } // subtract the space character (converts the ASCII number to the font index number) ch -= 32; // step through each byte of the character array for (int i=0; i&lt;charWidth; i++) { char b = pgm_read_byte_near(&amp;(font[ch][i])); for (int j=0; j&lt;charHeight; j++) { digitalWrite(LEDS[j], bitRead(b, 7-j)); } dwellDelay(); } //clear the LEDs for (int i = 0; i &lt; rows; i++) digitalWrite(LEDS[i] , LOW); dwellDelay(); } void printLetterLower(char ch){ // make sure the character is within the alphabet bounds (defined by the font.h file) // if it's not, make it a blank character if (ch &lt; 32 || ch &gt; 126){ ch = 32; } // subtract the space character (converts the ASCII number to the font index number) ch -= 32; // step through each byte of the character array for (int i=charWidth-1; i&gt;-1; i--) { char b = pgm_read_byte_near(&amp;(font[ch][i])); for (int j=0; j&lt;charHeight; j++) { digitalWrite(LEDS[j+1], bitRead(b,j)); } dwellDelay(); } //clear the LEDs for (int i = 0; i &lt; rows; i++) digitalWrite(LEDS[i] , LOW); // space between letters dwellDelay(); } bool touched(){ // returns true if touched, false if not. Light LED until touch released bool touchVal = digitalRead(touchPullUp); if (!touchVal){ while(!digitalRead(touchPullUp)){ // wait till touch release delay(10); digitalWrite(LEDS[mode], LOW); } //digitalWrite(LEDS[0], LOW); return (true); } else{ return (false); } } void checkButton(){ // check button for mode change and display current mode if (touched()){ mode += 1; if (mode &gt;= modes){ mode = 0; } EEPROM.write(0, mode); blipLEDs(); } } void blipLEDs(){ // something to show we are alive for(int LED=0; LED&lt;(sizeof(LEDS)/sizeof(int)); LED++){ digitalWrite(LEDS[LED], HIGH); delay(10); digitalWrite(LEDS[LED], LOW); } for(int LED=sizeof(LEDS)/sizeof(int); LED&gt;mode; LED--){ digitalWrite(LEDS[LED], HIGH); delay(10); digitalWrite(LEDS[LED], LOW); } digitalWrite(LEDS[mode], HIGH); } void EEPROMWritelong(int address, long value) { //This function will write a 4 byte (32bit) long to the eeprom at //the specified address to address + 3. //https://playground.arduino.cc/Code/EEPROMReadWriteLong //Decomposition from a long to 4 bytes by using bitshift. //One = Most significant -&gt; Four = Least significant byte byte four = (value &amp; 0xFF); byte three = ((value &gt;&gt; 8) &amp; 0xFF); byte two = ((value &gt;&gt; 16) &amp; 0xFF); byte one = ((value &gt;&gt; 24) &amp; 0xFF); //Write the 4 bytes into the eeprom memory. EEPROM.write(address, four); EEPROM.write(address + 1, three); EEPROM.write(address + 2, two); EEPROM.write(address + 3, one); } long EEPROMReadlong(long address){ //Read the 4 bytes from the eeprom memory. long four = EEPROM.read(address); long three = EEPROM.read(address + 1); long two = EEPROM.read(address + 2); long one = EEPROM.read(address + 3); //Return the recomposed long by using bitshift. return ((four &lt;&lt; 0) &amp; 0xFF) + ((three &lt;&lt; 8) &amp; 0xFFFF) + ((two &lt;&lt; 16) &amp; 0xFFFFFF) + ((one &lt;&lt; 24) &amp; 0xFFFFFFFF); } void clearArray(){ for(int i=0; i&lt;sizeof(charArray); i++){ // clear array charArray[i] = 0; } } </code></pre>
<p>When you first get one of those chips, it's always internally configured to down-clock the internal oscillator by 8. So, it's still running at 8MHz physical, but the actual chip clock speed is 1 MHz.</p> <p>If you tell the IDE it's the 8 MHz version (divider turned off), it will take ~8x longer to run any sort of delay (which is why you're seeing the 7.75s LED pulse rather than 1s).</p> <p>To fix this problem, set the IDE to the chip settings you want (8 MHz internal oscillator*), then click &quot;Burn Bootloader.&quot; This won't actually set the bootloader, as this chip doesn't use one, but it <em>will</em> set the internal fuses so the clock divider is turned off and it will work at 8 MHz as expected.</p> <p>Note that the programmer will still need to be set to the low speed (why it says &quot;SLOW, for <strong>new</strong> [emphasis mine] or 1 MHz parts&quot;) when you do the &quot;Burn Bootloader&quot; as the chip will otherwise be running too slowly at 1 MHz to receive the commands at the programmer's default speed (the other cause of the rc=-1 error, aside from bad wiring).</p> <p>Note that sometimes the programmer will also fail to work if any of the programming pins have LEDs or switches attached - are you removing the chip before programming, or is it still attached to the circuit? If the latter, also try isolating it before programming.</p> <p>*Make sure you <strong>do not</strong> select any of the external clock options unless you know what you're doing. Doing this will brick your chip <em>unless</em> you happen to have an external clock source of that type or a high voltage programmer. I'm not sure how those work, but they're a special (expensive) variant that uses a higher-than normal voltage to override the fuse settings even if the chip won't clock.</p>
91314
|shift-register|
74HC595N breaks when not connected to 5V
2022-11-15T08:33:40.993
<p>I'm trying to build a simple LED controller using this shift register, however when I remove the 5V power source, the device breaks down. The error message was : &quot;This device broke because of: Voltage at pin STCP is 5v, while maximum is Vcc = 0v&quot;. There isn't any current in the circuit to break it down. Can anyone explain to me why it behaves that way?</p> <p>Basically, I connected the output of the register to resistors and LEDS. Here is my wiring diagram: <a href="https://i.stack.imgur.com/bbFJy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bbFJy.jpg" alt="enter image description here" /></a></p> <p>Here is my code:</p> <pre><code>const int SER =8; //Serial Output to Shift Register const int LATCH =9; //Shift Register Latch Pin const int CLK =10; //Shift Register Clock Pin void setup() { //Set pins as outputs pinMode(SER, OUTPUT); pinMode(LATCH, OUTPUT); pinMode(CLK, OUTPUT); digitalWrite(LATCH, LOW); //Latch Low shiftOut(SER, CLK, MSBFIRST, B10101010); //Shift Most Sig. Bit First digitalWrite(LATCH, HIGH); //Latch High - Show pattern } void loop() { //Do nothing } </code></pre>
<p>Yes, you should not disconnect Vcc from a chip as long as you have active signal lines running to it, which have a voltage level different than ground. To be safe: Just remove the power from your whole circuit before removing the power lines - or only remove the power lines once you have removed all other connections.</p> <p>This depends on the used chip. But most chips with digital data/signal lines have internal protection diodes connected to the pins. If you provide a voltage above the limit, then a current can flow through the protection diode into the Vcc line of the chip. This is done to protect the internal hardware connected to the pin (since the whole chip can endure more than a single pin by its own).</p> <p>With removing the Vcc connection to the chip you are lowering Vcc to ground level, so way below the level of a HIGH signal line. Thus the current can flow through the pins protection diode to Vcc and feed power to the chip through the signal pin. But the protection diodes are not made for enduring a significant power draw for more than very short spikes. So when doing that you can fry the protection diodes. And you cannot predict, if it will fail short (creating a short between the pin and Vcc, preventing further communication through this pin) or fail open, in which case the chip might still work (if the pins internal hardware is still OK).</p> <p>For that reason some datasheets will define the voltage limits of the digital input pins dependent on Vcc. In the datasheet of the 75HC595 section 7.3 &quot;Recommended Operating Conditions&quot; you will see the &quot;V_I Input voltage&quot; with the limits to be 0V and Vcc.</p>
91319
|arduino-ide|communication|python|
Serial communication between python and Arduino nano BLE sense 33 for running six DC motor
2022-11-15T23:40:35.440
<p>I am controlling six DC motors by varying their voltage. I have figured out the voltage required for each motor in python; now it's time to send this voltage through Arduino Nano BLE Sense 33 to run the six DC motors via serial communication. Can anyone help me to figure out its solution?</p> <pre><code>Python Code: from time import sleep import serial import struct ser = serial.Serial('COM7', 9600) while True: ser.write(struct.pack('BBBBBB',200,210,220,230,240,180)) ## PWM ser.readline() sleep(.5) Arduino Code: const int ledPin[6] = {4, 7, 8, A5, 13, A0}; const int ledPin1[6] = {2, 6, 9, A4, 12, A1}; const int ledPin2[6] = {3, 5, 10, A3, 11, A2}; int x; void setup() { Serial.begin(9600); for (int k = 0; k &lt; 6; k++) { pinMode(ledPin[k], OUTPUT); pinMode(ledPin1[k], OUTPUT); pinMode(ledPin2[k], OUTPUT); } Serial.setTimeout(1); } void loop() { for (int i = 0; i &lt; 6; i++) { while (!Serial.available()); x = Serial.readString().toInt(); dir(ledPin[i], x, ledPin1[i], ledPin2[i]); } } float dir(int Pin, float x, int Lpin1, int Lpin2) { analogWrite(Pin, abs(x)); if (x &lt; 0) { digitalWrite(Lpin1, HIGH); digitalWrite(Lpin2, LOW); } else if (x &gt; 0) { digitalWrite(Lpin1, LOW); digitalWrite(Lpin2, HIGH); } else { digitalWrite(Lpin1, LOW); digitalWrite(Lpin2, LOW); } } </code></pre>
<p>Here is your Arduino <code>loop()</code> should look like:</p> <pre><code>void loop() { if(Serial.available() &gt; 0) { for (int i = 0; i &lt; 6; i++) { while (!Serial.available()); int x = Serial.read(); dir(ledPin[i], x, ledPin1[i], ledPin2[i]); } } } </code></pre> <p>Haven't tested it though.</p>
91343
|arduino-uno|voltage|voltage-protection|
power 12v solenoid from DC jack of Arduino Uno
2022-11-18T12:22:25.470
<p>I was wondering if it is possible to power up a 12V solenoid valve from the DC jack of the Arduino Uno, provided that I'm powering the Arduino from the same jack: <a href="https://i.stack.imgur.com/kdxfp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kdxfp.jpg" alt="enter image description here" /></a></p>
<p>Sure, that's the same as if you were directly soldering a second plug to your power supply. Just make sure the power supply delivers enough current for your solenoid (the power used by the Arduino will be comparably negligible).</p>
91382
|arduino-uno|serial|i2c|
Multiple unique I2C devices interfere
2022-11-22T06:55:22.100
<p>I'm trying to make a fairly simple program that interfaces with the <a href="https://www.adafruit.com/product/1980" rel="nofollow noreferrer">Adafruit TSL2591 light sensor</a> as well as a <a href="https://www.amazon.ca/MAX30102-Detection-Concentration-Compatible-Arduino/dp/B07ZQNC8XP" rel="nofollow noreferrer">MAX30102 pulse oximeter</a>. They both use I2C for communication. I'm using the recommended libraries for both, <a href="https://github.com/adafruit/Adafruit_TSL2591_Library" rel="nofollow noreferrer">Adafruit_TSL2591_Library <em>Version 1.4.3</em></a> and <a href="https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library" rel="nofollow noreferrer">SparkFun_MAX3010x_Sensor_Library <em>Version 1.1.2</em></a> respectively. This is all running on an Arduino UNO, although I will be transferring it to a NANO in the near future. All of the following is using <em>Version 2.0.2</em> of the Arduino IDE.</p> <p>The issue I'm running into is that both sensors will work perfectly fine in isolation, but when trying to run at the same time it locks up and outputs nothing.</p> <p><a href="https://github.com/adafruit/Adafruit_TSL2591_Library/blob/db71874052f1aab68250160689f8d158fef53ad4/examples/tsl2591/tsl2591.ino" rel="nofollow noreferrer">Example code</a> that works for the Light sensor.</p> <p><a href="https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library/blob/72d5308df500ae1a64cc9d63e950c68c96dc78d5/examples/Example8_SPO2/Example8_SPO2.ino" rel="nofollow noreferrer">Example code</a> that works for the pulse oximeter.</p> <p>I know my wiring is good because the sensors work individually with either program even when both sensors are plugged in simultaneously.</p> <p>The code that almost works:</p> <pre><code>#include &lt;Wire.h&gt; #include &quot;MAX30105.h&quot; #include &quot;spo2_algorithm.h&quot; #include &lt;Adafruit_Sensor.h&gt; #include &quot;Adafruit_TSL2591.h&quot; MAX30105 particleSensor; const byte LUX_ADDR = 0x29; const byte OX_ADDR = 0x57; Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); #define MAX_BRIGHTNESS 255 #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) //Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format //To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-bit data. uint16_t irBuffer[100]; //infrared LED sensor data uint16_t redBuffer[100]; //red LED sensor data #else uint32_t irBuffer[100]; //infrared LED sensor data uint32_t redBuffer[100]; //red LED sensor data #endif int32_t bufferLength; //data length int32_t spo2; //SPO2 value int8_t validSPO2; //indicator to show if the SPO2 calculation is valid int32_t heartRate; //heart rate value int8_t validHeartRate; //indicator to show if the heart rate calculation is valid void setup() { Serial.begin(115200); // initialize serial communication at 115200 bits per second: // Initialize sensor if (!particleSensor.begin(Wire, I2C_SPEED_FAST, OX_ADDR)) //Use default I2C port, 400kHz speed { Serial.println(F(&quot;MAX30105 was not found. Please check wiring/power.&quot;)); while (1); } byte ledBrightness = 60; //Options: 0=Off to 255=50mA byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32 byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200 int pulseWidth = 411; //Options: 69, 118, 215, 411 int adcRange = 4096; //Options: 2048, 4096, 8192, 16384 particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings light_sensor_details(); light_sensor_configure(); } void loop() { bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps //read the first 100 samples, and determine the signal range for (byte i = 0 ; i &lt; bufferLength ; i++) { while (particleSensor.available() == false) //do we have new data? particleSensor.check(); //Check the sensor for new data redBuffer[i] = particleSensor.getRed(); irBuffer[i] = particleSensor.getIR(); particleSensor.nextSample(); //We're finished with this sample so move to next sample Serial.print(F(&quot;red=&quot;)); Serial.print(redBuffer[i], DEC); Serial.print(F(&quot;, ir=&quot;)); Serial.println(irBuffer[i], DEC); } //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples) maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &amp;spo2, &amp;validSPO2, &amp;heartRate, &amp;validHeartRate); //Continuously taking samples from MAX30102. Heart rate and SpO2 are calculated every 1 second while (1) { //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top for (byte i = 25; i &lt; 100; i++) { redBuffer[i - 25] = redBuffer[i]; irBuffer[i - 25] = irBuffer[i]; } //take 25 sets of samples before calculating the heart rate. for (byte i = 75; i &lt; 100; i++) { while (particleSensor.available() == false) //do we have new data? particleSensor.check(); //Check the sensor for new data redBuffer[i] = particleSensor.getRed(); irBuffer[i] = particleSensor.getIR(); particleSensor.nextSample(); //We're finished with this sample so move to next sample //send samples and calculation result to terminal program through UART Serial.print(F(&quot;red=&quot;)); Serial.print(redBuffer[i], DEC); Serial.print(F(&quot;, ir=&quot;)); Serial.print(irBuffer[i], DEC); Serial.print(F(&quot;, HR=&quot;)); Serial.print(heartRate, DEC); Serial.print(F(&quot;, HRvalid=&quot;)); Serial.print(validHeartRate, DEC); Serial.print(F(&quot;, SPO2=&quot;)); Serial.print(spo2, DEC); Serial.print(F(&quot;, SPO2Valid=&quot;)); Serial.println(validSPO2, DEC); } //After gathering 25 new samples recalculate HR and SP02 maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &amp;spo2, &amp;validSPO2, &amp;heartRate, &amp;validHeartRate); light_sensor_read(); } } void light_sensor_details () { sensor_t sensor; tsl.getSensor(&amp;sensor); delay(500); } void light_sensor_configure () { delay(200); tsl.setGain(TSL2591_GAIN_MED); delay(200); tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); delay(200); tsl2591Gain_t gain = tsl.getGain(); } void light_sensor_read() { uint32_t lum = tsl.getFullLuminosity(); uint16_t ir, full; ir = lum &gt;&gt; 16; full = lum &amp; 0xFFFF; Serial.print(F(&quot;Lux: &quot;)); Serial.println(tsl.calculateLux(full, ir), 6); } </code></pre> <p>The pulse oximeter part will function correctly with the last two lines of <code>setup()</code> and the last line of <code>loop()</code> commented. <code>light_sensor_details();</code>,<code>light_sensor_configure();</code> and <code>light_sensor_read();</code> respectively. The output with these two lines commented is as follows:</p> <pre><code>red=4229, ir=3967 red=4530, ir=3790 red=3629, ir=4104 red=3563, ir=5211 red=4555, ir=9076 red=7091, ir=16753 red=13068, ir=23695 red=10753, ir=11273 ... red=31031, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=31044, ir=48283, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=31017, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=31027, ir=48306, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=31022, ir=48291, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=31016, ir=48271, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=30997, ir=48294, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=30981, ir=48268, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=30966, ir=48289, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 red=30981, ir=48293, HR=-999, HRvalid=0, SPO2=-999, SPO2Valid=0 ... </code></pre> <p>(An expected output given my finger wasn't on the sensor for this.)</p> <p>If I uncomment the 2nd last line of <code>setup()</code> then it still manages to show the red and ir values but never starts to show the calculated values. Instead it will occasionally (unpredictably) show chunks of invalid characters, like so:</p> <p><a href="https://i.stack.imgur.com/zlXD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zlXD8.png" alt="" /></a></p> <p>Going further and uncommenting the other two lines simply locks up and prints nothing to the serial monitor.</p> <p>Also to clarify the three light sensor related functions do work in their own file, I'll include it here for the sake of completeness:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_Sensor.h&gt; #include &quot;Adafruit_TSL2591.h&quot; Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); void setup() { Serial.begin(115200); // initialize serial communication at 115200 bits per second: light_sensor_details(); light_sensor_configure(); } void loop() { light_sensor_read(); } void light_sensor_details () { sensor_t sensor; tsl.getSensor(&amp;sensor); delay(500); } void light_sensor_configure () { tsl.setGain(TSL2591_GAIN_MED); tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS); tsl2591Gain_t gain = tsl.getGain(); } void light_sensor_read() { uint32_t lum = tsl.getFullLuminosity(); uint16_t ir, full; ir = lum &gt;&gt; 16; full = lum &amp; 0xFFFF; Serial.print(F(&quot;Lux: &quot;)); Serial.println(tsl.calculateLux(full, ir), 6); } </code></pre> <p>Running this outputs:</p> <pre><code>... Lux: 41.283641 Lux: 36.879783 Lux: 10.549278 Lux: 2.826355 Lux: 11.158865 Lux: 1.489472 Lux: 1.713600 Lux: 31.461915 Lux: 48.357471 Lux: 50.827312 ... </code></pre> <p>I think the issue is something to do with the I2C bus, but because both sensors use their own libraries for communication I can't use the online examples for manually starting and stopping communication with the <em>Wire</em> library. I can't find anyone else online with this issue or any examples of multiple I2C devices that I'm able to make use of (to my understanding).</p> <p>Am I on the right track with it being an I2C problem? Is there a simple fix that I'm simply unaware of? Or is there a separate issue with my code?</p> <p>Many thanks for any help!</p> <p>Edit: Changed Title</p>
<p>It turns out the issue was with limited dynamic memory. The MAX30105 requires a lot of space for its calculations and adding anything else, whether that be another sensor or even a software serial connection, would crash it. Even using <code>Serial.println()</code> put it over the edge. <strong>It became unstable beyond around 89% full, or about 250 bytes of empty dynamic memory.</strong></p> <p>I ended up using a 32u4 equipped board to solve the memory issue and it worked perfectly after that.</p> <p>It had nothing to do with I2C.</p>
91394
|arduino-uno|
How do I put a LiquidCrystal_I2C class in a Lcd class?
2022-11-23T00:03:45.280
<p>I want to make my main code cleaner so I was thinking of making a Lcd class which I can use every time I need to print on lcd. So my main code every time I try to print text I need to call :</p> <pre><code>lcd.clear(); lcd.setCursor(1,0); lcd.print(&quot;Text 1st line&quot;); lcd.setCursor(1,0); lcd.print(&quot;Text 2nd line&quot;); </code></pre> <p>The problem is I need to create a class called Lcd which initialises the LCD display through LiquidCrystal_I2C.h and calls it's functions in order to print as I want. Below I will post some code which is totally wrong but I guess it can give you the idea of what I am trying to do:</p> <p><strong>LcdControl.hpp</strong></p> <pre><code>class LcdControl{ public: LcdControl(); void printOnLcd(int data,int column,int line); void printOnLcd(char data,int column,int line); }; </code></pre> <p><strong>LcdControl.cpp</strong></p> <pre><code>#include &lt;LiquidCrystal_I2C.h&gt; #include &lt;Arduino.h&gt; #include &quot;LcdControl.hpp&quot; LcdControl::LcdControl(){ LiquidCrystal_I2C lcd(0x27,20,4); lcd.init(); lcd.init(); lcd.backlight(); } void LcdControl::printOnLcd(int data,int column,int line){ lcd.clear(); lcd.setCursor(column,line); lcd.print(data); } void LcdControl::printOnLcd(char data,int column,int line){ lcd.clear(); lcd.setCursor(column,line); lcd.print(data); } </code></pre>
<p>You could also use an inheritance model where the the base class is the original library LiquidCrystal_I2C and you simply create a new derived class, in this case LcdControl. In LcdControl, you simply pack in your additional methods. The only slight complexity is that you have to invoke the constructor of the base class LiquidCrystal_I2C when the constructor of the derived class LcdControl is called.</p> <p>Here it is in a simulation: <a href="https://wokwi.com/projects/349238619253244498" rel="nofollow noreferrer">https://wokwi.com/projects/349238619253244498</a></p> <p>Code:</p> <pre><code>#include &lt;LiquidCrystal_I2C.h&gt; class LcdControl : public LiquidCrystal_I2C { public: LcdControl( uint8_t lcd_Addr, uint8_t lcd_cols, uint8_t lcd_rows) : // base class constructor LiquidCrystal_I2C ( lcd_Addr, lcd_cols, lcd_rows ) { } void printOnLcd(const char * data, int column, int line) { LcdControl::clear(); LcdControl::setCursor(column, line); LcdControl::print(data); } } ; LcdControl lcd(0x27, 20, 4); void setup() { Wire.begin() ; lcd.init() ; lcd.backlight(); lcd.printOnLcd( &quot;hello world2&quot;, 0 , 0 ) ; delay(1000) ; lcd.printOnLcd( &quot;hello world3&quot;, 1 , 2 ) ; } void loop() { } </code></pre>
91399
|audio|
3.5mm jack frequency response at low frequency (20Hz)
2022-11-23T08:01:47.033
<p>I'm trying to drive a bass shaker at low frequencies, down to 20Hz, with an Arduino. Has anyone ever done something like this?</p> <p>I found an audio amp that takes in 3.5mm aux, and I was hoping to get a 3.5mm jack to drive the amp from an Arduino. However, I can't find any technical specs on audio jacks so I am not sure if they support low frequencies. Are there any audio jacks with frequency response data available?</p> <p>If not, are there other ways to achieve this?</p>
<p>You can send DC (i.e. 0 Hz) through an audio jack, so I would not worry about its low-frequency response.</p>
91422
|arduino-uno|sensors|led|
Fading out a led with reed switch loop
2022-11-25T11:11:42.520
<p>I was hoping to get some help on the fading led which I am working on.</p> <p>For my project I need to have a led, which when it is placed next to a magnet, continuously shines, but as soon as it is taken away it has to fade out in a certain amount of time. So far I managed to write the code which detects when the light is taken away from the magnet and fades out, but when the magnet is nearby again, the led lights up and keeps shining, no matter if I take it away from the magnet or not. So how I could solve this? I tried to exit the loop function, but then this process happens only once, which is not what I want. I am also using reed switch to detect the magnet, but if you have other sensor suggestions, let me know. I'm including the code down here.</p> <p>Thank you for your help in advance:)</p> <pre><code>int ledPin = 9; int brightness = 255; int fadeAmount = 5; const int reedPin = 2; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); pinMode(reedPin, INPUT_PULLUP); } void loop() { int proximity = digitalRead(reedPin); if (proximity == HIGH) { Serial.println(&quot;Switch opened&quot;); while (brightness &gt;= 0) { analogWrite(ledPin, brightness); brightness = brightness - fadeAmount; delay(30); Serial.println(brightness); } } else { Serial.println(&quot;Switch closed&quot;); analogWrite(ledPin, brightness); Serial.println(brightness); } } </code></pre>
<p>Your current problem probably comes from the fact, that you execute the fading loop, even if <code>brightness</code> is already zero, and that you don't reset it to zero after fading.</p> <pre><code>while(brightness &gt;= 0){ ... brightness = brightness - fadeAmount; ... } </code></pre> <p>Imagine we are at the point, where <code>brightness</code> is 5. The while condition is true, since 5 &gt; 0. Then we execute the code in the loop, setting <code>brightness</code> to 0. We again check the while condition. It is still true, since <code>0&gt;=0</code>. So after executing the code in the loop again, <code>brightness</code> is now -5. But <code>analogWrite()</code> only takes a 1 byte unsigned (!) integer, aka <code>uint8_t</code>, while <code>int</code> is a 2 byte signed (!) integer. So only the lower byte of that integer will be used and interpreted as unsigned. So -5 gets interpreted as 251, which you see as lighting up in full brightness.</p> <p>Easy fix would be to set <code>brightness</code> to zero after the while loop:</p> <pre><code>brightness = 0; </code></pre> <hr /> <p>That said, I would suggest a completely different route, which will make your code way more responsive, by using the non-blocking coding principle from the <code>BlinkWithoutDelay</code> example, that comes with the Arduino IDE.</p> <p>As you did, I would use a global <code>brightness</code> and <code>fadeAmount</code> variable, but also one to hold a timestamp:</p> <pre><code>unsigned long timestamp=0; </code></pre> <p>Then in <code>loop()</code> we can first do the fading to zero by using the <code>millis()</code> function as a clock:</p> <pre><code>if(millis()-timestamp &gt; 30){ brightness = brightness - fadeAmount; if(brightness &lt; 0) brightness = 0; timestamp = millis(); } </code></pre> <p>That will decrement the <code>brightness</code> variable to zero without blocking with a <code>delay()</code>. The speed can be changed by changing the number <code>30</code> to something different. This number has the unit milliseconds.</p> <p>Then we can check for the reed switch and set <code>brightness</code> to 255, if it is activated:</p> <pre><code>if(!digitalRead(reedPin)){ // reedPin is LOW brightness = 255; } </code></pre> <p>So as long as the magnet is at the reed switch, this code will set <code>brightness</code> to 255.</p> <p>And finally we need to write the value of <code>brightness</code> to the output pin:</p> <pre><code>analogWrite(ledPin, brightness); </code></pre> <p>So as a full code:</p> <pre><code>int ledPin = 9; int reedPin = 2; int brightness = 0; int fadeAmount = 5; unsigned long timestamp = 0; void setup(){ pinMode(ledPin, OUTPUT); pinMode(reedPin, INPUT_PULLUP); } void loop(){ if(millis()-timestamp &gt; 30){ brightness = brightness - fadeAmount; if(brightness &lt; 0) brightness = 0; timestamp = millis(); } if(!digitalRead(reedPin)){ // reedPin is LOW brightness = 255; } analogWrite(ledPin, brightness); } </code></pre> <p>I've tested this with a normal button (currently no reed switch here). It should work as expected.</p>
91429
|arduino-uno|led|pwm|transistor|
PWM with a TRANSISTOR on flexible LED filament
2022-11-25T16:03:55.117
<p>I would like to create a custom lighting, with <strong>PWM</strong> capability, powered <strong>from battery</strong>. I would like to use <strong>flexible led filaments</strong>, and since those <strong>consumes more than 40mA</strong>, I can't use them directly on a board. I found a link explaining to use a <strong>MOSFET</strong> transistor, to dim my leds. So the transistor that I need would be one with a 5v power supply, and a 5v Voltage input.</p> <p>The problem is that I can't find any transistor matching those specs. I also noticed that they have a heatsink, which mean that they need to dissipate heat, and are therefore not power efficient (which i do not like). Am I missing something ?</p> <p>Any help will be apreciated, thanks !</p>
<p>You cannot find a MOSFET with that exact rating, because transistors can be used with all voltages inside of their specific limits. Most MOSFETs can be used with way higher voltages than 5V.</p> <p>What you need is a logic level MOSFET, which means, that it will be in saturation (aka being fully ON) at the typical logic level of 5V on its gate. In the datasheet of a MOSFET you will find a diagram which shows the drain current depending on the gate-source voltage. At your logic level (5V in this case) you want the curve approaching a plateau.</p> <p>Another important value is <code>R_DS(on)</code>. That is the resistance of the MOSFET when its on. The lower the resistance, the lower will the power lost to heat.</p> <blockquote> <p>I also noticed that they have a heatsink, which mean that they need to dissipate heat, and are therefore not power efficient (which i do not like).</p> </blockquote> <p>Every MOSFET dissipates some energy as heat, since no MOSFET can have <code>R_DS(on)</code> of zero. The typical heat sink flap is meant to dissipate the heat for keeping the MOSFETs temperature in the specified range, even when drawing the maximum specified current. The datasheet of a MOSFET has a section with maximum ratings. There you should see the maximum drain current <code>I_D</code> with its corresponding needed temperatures. For example have a look at <a href="https://eu.mouser.com/datasheet/2/308/1/FDP5800_D-1808068.pdf" rel="nofollow noreferrer">this datasheet</a> of a random logic level MOSFET from mouser. There is no specification of how hot the case gets with a specific current, since this depends on the suroundings, but the datasheet states, that it will support up to 80A, when you keep the case to a temperature of 25°C.</p> <p>It also states what electrical power it can dissipate with its package: <code>P_D</code>. You should look at how much current you need for your LED filament. You can calculate the dissipating power with <code>P = R * I²</code> (P being power, R the resistance R_DS(on) and I the current through the MOSFET).</p>
91438
|arduino-ide|arduino-nano|gps|tinygps|u8glib|
How "fast" could GPS data be refreshed while moving and does it depend on the mcu?
2022-11-26T23:54:55.310
<p>I'm using Nano Every and SIM33EAU GPS module for my project and today I went riding shotgun to test how it works when moving on the road. I am using u8g2 library and one of the things that I have printed on the screen is gps.course.deg - which is as the name suggest, course of the GPS module's movement in degrees.</p> <p>Next to my Arduino device I had a phone with some compass app, and the course was somewhat correct while we were moving at normal traffic speed, but the update rate was vastly different and I don't know why. The only &quot;delay&quot; in the sketch I have is this;</p> <pre><code> if (gps.location.isUpdated()) { Serial.print(F(&quot;Lat Lon = &quot;)); Serial.print(gps.location.lat(), 6); Serial.print(&quot;, &quot;); Serial.println(gps.location.lng(), 6); } else if (millis() - last &gt; 500) ... </code></pre> <p>I wasn't able to check the Serial Monitor as I didn't have a laptop, so only reading from GPS module was what was being printed on the small OLED screen. So is the lagging update something on the GPS module side and how it works, or is it perhaps OLED not being able to refresh?</p>
<p>GPS modules deliver position updates in very different frequencies, depending on model and configuration (where changeable). Cheaper modules only provide an update every 1 second, while better ones have 5 or 10 Hz position update. Check the documentation for your module to get that information.</p> <p>Additionally, it is of course possible to &quot;cheat&quot;, by calculating an extrapolation, using the last position, direction and speed. Since speed and direction don't typically change very quickly, that works quite well and can give position updates at arbitrary rates.</p>
91452
|arduino-uno|led|wifi|home-automation|
LEDs controlled by PHONE on ESP32
2022-11-28T17:47:51.343
<p>I am having doubts with a project I'm making. My project involves a <strong>sets of LEDs stripes, among which some are controlled from a smartphone, and some automated</strong>. The LED strips are connected to an <strong>Arduino</strong>, that would receive commands from a phone. Here is a scheme, with essentials elements I marked for my project :</p> <ul> <li><strong>A development board, with wifi</strong> support</li> <li>a framework/program allowing the smartphone to <strong>communicate with the board</strong></li> <li>And an <strong>Android app</strong> with a color interface, to change LEDs colors</li> </ul> <p>I made some research:</p> <ol> <li>I found a lot of boards, and eventually choose <strong>ESP32 boards</strong> (Good ones).</li> <li>I found a <strong>WLED</strong> system, that meet my requirements</li> <li>I know <strong>Home assistant</strong>, that offers <strong>more possibility</strong> than WLED</li> <li>I <strong>won't</strong> use <strong>local server</strong>, since it is not easy to use for other people (family members for example).</li> </ol> <p><strong>WLED</strong> seems to be very useful, and easy to use. But, <em>from what I understood</em>, if I installed WLED on my board, I would have to dedicate the entire board to the WLED program, and therefore i wouldn't be able to upload any other custom code to my board. Since <strong>I want some LEDs to be remotely controlled, and the others to run on an programmed loop</strong>, I don´t know if it´s a good idea</p> <p><strong>Home assistant</strong> is more complete, and shouldn't have the problem mentioned above. It can also support several devices, and can have many boards registered on it. I would like, later, to expand Home Assistant to other projects, this is why starting Home assistant now is a good idea. Thus, <strong>I believe I will go for Home Assistant</strong></p> <hr /> <p><strong>I now struggle with the following issues:</strong></p> <ol> <li>I am unsure if i understood correctly, but <strong>I read some people complaints about certains ESP32 boards which need complete wifi configuration (networking stack)</strong>, and are complicated to install. This is why I wanted adafruit boards, supposing that their chip has already an uploaded code. Is that right ?</li> <li>I also read on the internet that after compiling the networking stack on ESP8266 boards, there isn't much space left for the program to run. <strong>Given that I choose the ESP32, with more space, do I have plenty of space for my code, or is it still limited ?</strong></li> <li>WLED seemed fine, but as I said, I'm not sure if I can upload code. <strong>Can I upload custom code and WLED system to the board, or is it entirely focused on WLED ?</strong></li> </ol> <p>Thanks to anyone who could bring some clarification to me, I will appreciate it !</p>
<blockquote> <p>I am unsure if i understood correctly, but I read some people complaints about certains ESP32 boards which need complete wifi configuration (networking stack), and are complicated to install. This is why I wanted adafruit boards, supposing that their chip has already an uploaded code. Is that right ?</p> </blockquote> <p>I don't know what complaints you have seen (since you didn't like to them), so that I cannot talk about the context. I have used several different ESP boards. The ones, that are a bit difficult to program, were the boards without a USB interface. That is mostly the case with the very small boards.</p> <p>Yes, Adafruit is a reputable source for such boards. Though I also never had problems with typical ESP dev boards from other sources, like the company named like the big river in south america. Install the ESP32 core in the Arduino IDE, connect the board via USB and program it.</p> <blockquote> <p>I also read on the internet that after compiling the networking stack on ESP8266 boards, there isn't much space left for the program to run. Given that I choose the ESP32, with more space, do I have plenty of space for my code, or is it still limited ?</p> </blockquote> <p>The ESP8266 is smaller, yes, but I still used it and could still write quite big programs while using Wifi. Here one fact is also important: The number after the ESP describes the chip itself, but most boards use an external flash memory chip. Thus the maximum program size depends on how big of a flash chip the board manufacturer uses for the board. You can find that information wherever you buy your board.</p> <p>Either way, with an ESP32 you are in every case good to go and you will have plenty of resources for whatever you want to do (including enough free pins). If you want to use WLED, you can check for compatible boards in their <a href="https://github.com/Aircoookie/WLED/wiki/Compatible-hardware" rel="nofollow noreferrer">wiki at github</a>.</p> <blockquote> <p>WLED seemed fine, but as I said, I'm not sure if I can upload code. Can I upload custom code and WLED system to the board, or is it entirely focused on WLED ?</p> </blockquote> <p>Only one program can run at the ESP at a time (technically the ESP has 2 cores, so executes 2 things simultaneously, but one core is used for handling Wifi, so for user code only one core is left). WLED is meant as a ready to use firmware, so no writing of custom code.</p> <p>You should first think about, what you would want to do with your code. You haven't specified, what exactly your custom code should do while WLED handles the LED strips. Maybe the functionality of WLED is enough for you.</p> <p>Otherwise you can loop for 2 things with WLED:</p> <ul> <li>Search in the WLED code/documentation for a place to plug your own code into a function. WLED might give you that possibility (cannot search that myself now, since the official documentation site fails with a certificate problem for me and I cannot open it, even if I accept the risk in my browser).</li> <li>If the above is not possible, you can try changing the source code of WLED to also handle your own code. That might be rather difficult, especially for a beginner. Digging in someone elses code while being a beginner is a very steep learning curve.</li> </ul> <p>If both of this is not fitting for you and you still want to execute your own code, then you will have to write the code yourself entirely.</p> <hr /> <p>Besides my answers above, I would suggest, that you think about what features you need and which you don't need exactly. The options, that you listed, are vastly different.</p> <p>Home Assistent especially is a very big project, which is powerful, but also complex and difficult to setup. Also keep in mind, that Home Assistent is a program, that needs to run somewhere, and it will not run on the ESP. So you need something like a Raspberry Pi (or any other small home server, which you run 24/7), where you install and configure Home Assistent, before you can even start with the ESPs.</p> <p>If all you want to do is controlling some LED strips, then Home Assistent is overkill. If you plan to automate your home further, then Home Assistent can be a good choice. Though then your project isn't only about LED strips.</p>
91460
|attiny|avr|oscillator-clock|avr-gcc|
slower clock frequency than expected on attiny202
2022-11-29T09:03:18.853
<p>I am programming an attiny202 which as per <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny202-402-AVR-MCU-with-Core-Independent-Peripherals_and-picoPower-40001969A.pdf" rel="nofollow noreferrer">datasheet</a> can run up to 20Mhz, but after compiling/uploading this simple code to the attiny202 and watch the PA2 pin on the oscilloscope, I see that the pin oscilates at ~2.5MHz which is around 10x slower than I would expect, this is even I disable prescaling, am I missing something? (I am new into programming microcontrollers)</p> <blockquote> <p>note: VCC is 5V (from lab bench PSU)</p> </blockquote> <p>main.c</p> <pre class="lang-c prettyprint-override"><code>#include &lt;avr/io.h&gt; int main(void) { // no prescaling (if lesss than 4.5V, this is overclocking) _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0); PORTA_DIR = _BV(2); while(1) { PORTA_OUTTGL = _BV(2); } } </code></pre> <p>Makefile</p> <pre><code>PRG = main CC = avr-gcc MCU_TARGET = attiny202 OPTIMIZE = -Os OBJCOPY = avr-objcopy UART = /dev/ttyUSB0 all: $(PRG).elf $(PRG).hex $(PRG).elf: $(PRG).c » $(CC) -g -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) $(PRG).c -o $(PRG).elf %.hex: %.elf » $(OBJCOPY) -j .text -j .data -O ihex $&lt; $@ clean: » rm *.elf *.hex burn: $(PRG).hex » pymcuprog -t uart -d $(MCU_TARGET) -u $(UART) write -f $(PRG).hex --erase --verify </code></pre> <p>bitmaps from oscilloscope:</p> <p>-<a href="https://i.stack.imgur.com/oS5vf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oS5vf.png" alt="enter image description here" /></a></p> <p>same picture with more measurement information:</p> <p><a href="https://i.stack.imgur.com/LOf6q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LOf6q.png" alt="enter image description here" /></a></p>
<p>Just as a complement to chrisl's answer, if you disassemble the compiled program, you should see that your infinite loop looks like this:</p> <pre class="lang-lisp prettyprint-override"><code>1: sts 0x0407, r24 ; write to PORTA_OUTTGL rjmp 1b ; jump back to previous instruction </code></pre> <p>These instructions take two cycles each, for a total of four cycles per loop iteration. The loop is thus expected to run at F_CPU÷4 = 5 MHz. Since a cycle of the output waveform takes two toggles, you expect to see 2.5 MHz on the oscilloscope.</p> <p>You should be able to speed this up by writing to the virtual port register <code>VPORTA_IN</code> instead of <code>PORTA_OUTTGL</code>. Virtual port registers are equivalent to regular port registers, but they are mapped into the I/O space of the microcontroller. This allows the compiler to replace the <code>sts</code> instruction by the shorter and faster <code>out</code> instruction. The loop should then complete in only 3 CPU cycles and output a waveform at 3.33 MHz.</p>
91483
|arduino-mega|
Use Arduino MEGA generate 40kHz multiple square wave signal with 10 phase
2022-12-01T12:38:56.167
<p>I want to use Arduino-mega generate multiple square wave signal,the siganl is 40kHz and it can be used to drive ultrasonic transducer.</p> <p>So,I use the trategy in article &quot;<a href="https://ieeexplore.ieee.org/document/8094247" rel="nofollow noreferrer">Ultraino: An Open Phased-Array System for Narrowband Airborne Ultrasound Transmission</a>&quot;,which apply 10 bit signal with sequence of '0' or '1' in PORTA,PORTC...etc to get a square wave signal like Fig 1.</p> <p><a href="https://i.stack.imgur.com/xAe7X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xAe7X.jpg" alt="Fig.1 square wave signal" /></a></p> <p>Fig.1 square wave signal</p> <hr /> <p>Then I change the sequence pattern to shift phase,and just only 10 phases,some problem happen.</p> <p>I am curious about the principle of this method:</p> <ol> <li><p>Why the sequence can generate signal with 40kHz?Does it mean Arduino will cost serval microseconds executing command like <code>POTRA=0x1</code>. I try to change the length of the array,it will no longer generate the square wave well.</p> </li> <li><p>When I execute the shift function <code>shiftPhase</code>,it have 10 phase.In 5 phase it will move the square wave like Fig.2,the other 5 phase will be like Fig3,the duty of square wave is changed,just like inverted.So,how does it happen,just with change the sequence of 0,1?</p> </li> </ol> <p><a href="https://i.stack.imgur.com/8xGIO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8xGIO.jpg" alt="Fig.2 shift wave success" /></a> Fig.2 shift wave success</p> <hr /> <p><a href="https://i.stack.imgur.com/8F3p9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8F3p9.jpg" alt="Fig.3 shift wave failed" /></a> Fig.3 shift wave failed</p> <hr /> <p>the code I use is:</p> <pre><code>#include &lt;avr/sleep.h&gt; #include &lt;avr/power.h&gt; #define N_PATTERNS 1 #define N_PORTS 10 #define N_DIVS 10 #define COMMAND_SWITCH 0b00000000 #define COMMAND_DURATION 0b00110000 #define MASK_DURATION 0b00111111 #define COMMAND_COMMITDURATIONS 0b00010000 #define WAIT(a) __asm__ __volatile__ (&quot;nop&quot;) #define OUTPUT_WAVE(pointer, d) PORTA = pointer[d*N_PORTS + 0]; PORTC = pointer[d*N_PORTS + 1]; PORTL = pointer[d*N_PORTS + 2]; PORTB = pointer[d*N_PORTS + 3]; PORTK = pointer[d*N_PORTS + 4]; PORTF = pointer[d*N_PORTS + 5]; PORTH = pointer[d*N_PORTS + 6]; PORTD = pointer[d*N_PORTS + 7]; PORTG = pointer[d*N_PORTS + 8]; PORTJ = pointer[d*N_PORTS + 9] static byte bufferA[N_PATTERNS * N_DIVS * N_PORTS]; static byte bufferB[N_PATTERNS * N_DIVS * N_PORTS]; static byte animation[100] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, }; String str=&quot;&quot;; void shiftPhase(byte* p,int len,int inter,int stepsize,byte id) { byte mask=0xff-id; byte q[10]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0}; for(int i=0;i&lt;10;i++) { q[i]=p[i*inter]; } for(int i=0;i&lt;10;i++) { p[i*inter]=(q[(i+stepsize+10)%10]&amp;id)|(mask&amp;q[i]); } } void setup() { //set as output ports A C L B K F H D G J DDRA = DDRC = DDRL = DDRB = DDRK = DDRF = DDRH = DDRD = DDRG = DDRJ = 0xFF; //low signal on all of them PORTA = PORTC = PORTL = PORTB = PORTK = PORTF = PORTH = PORTD = PORTG = PORTJ = 0x00; //clear the buffers for (int i = 0; i &lt; (N_PATTERNS * N_DIVS * N_PORTS); ++i) { bufferA[i] = bufferB[i] = 0; } for (int i = 0; i &lt; 100; ++i) { bufferA[i] = animation[i]; } // disable everything that we do not need ADCSRA = 0; // ADC power_adc_disable (); power_spi_disable(); power_twi_disable(); power_timer0_disable(); power_usart1_disable(); power_usart2_disable(); Serial.begin(9600); byte bReceived = 0; bool byteReady = false; bool emittingA = true; byte* emittingPointerH = &amp; bufferA[0]; byte* emittingPointerL = &amp; bufferA[N_PORTS * N_DIVS / 2]; LOOP: OUTPUT_WAVE(emittingPointerH, 0); OUTPUT_WAVE(emittingPointerH, 1); OUTPUT_WAVE(emittingPointerH, 2); OUTPUT_WAVE(emittingPointerH, 3); OUTPUT_WAVE(emittingPointerH, 4); OUTPUT_WAVE(emittingPointerL, 0); OUTPUT_WAVE(emittingPointerL, 1); OUTPUT_WAVE(emittingPointerL, 2); OUTPUT_WAVE(emittingPointerL, 3); OUTPUT_WAVE(emittingPointerL, 4); byteReady = Serial.available(); if(byteReady!=0) { str=&quot;&quot;; str=char(Serial.read()); Serial.println(str); if(str==&quot;1&quot;) { shiftPhase(bufferA,10,10,1,0x1); } if(str==&quot;2&quot;) { shiftPhase(bufferA,10,10,-1,0x1); } } while(Serial.read()&gt;=0){} goto LOOP; } void loop() {} </code></pre> <p>Thanks a lot!</p> <p>The code of the article can be see in <a href="https://github.com/asiermarzo/Ultraino/blob/master/DriverBoards/ArduinoMega64/firmware/DriverMEGAStatic/DriverMEGAStatic.ino" rel="nofollow noreferrer">link</a>.</p>
<p>Shiny100 asked:</p> <blockquote> <p>Does it mean Arduino will cost several microseconds executing command like <code>POTRA=0x1</code>.</p> </blockquote> <p>I tried compiling <code>POTRA=0x1</code> and I got this:</p> <pre class="lang-lisp prettyprint-override"><code>ldi r24, 0x01 ; load 0x1 into register r24 out 0x02, r24 ; output register r24 to PORTA (I/O address 0x02) </code></pre> <p>These are both single cycle instructions, so the sequence takes 2 cycles, i.e. 0.125 µs at 16 MHz. Your code, however, does a lot more that that. The macro <code>OUTPUT_WAVE()</code> involves reading ten values from RAM and writing them to ten different ports. The first call to this macro gets compiled into this:</p> <pre class="lang-lisp prettyprint-override"><code>lds r24, 0x028D ; r24 = bufferA[0] out 0x02, r24 ; PORTA = r24 lds r24, 0x028E ; r24 = bufferA[1] out 0x08, r24 ; PORTC = r24 lds r24, 0x028F ; r24 = bufferA[2] sts 0x010B, r24 ; PORTL = r24 lds r24, 0x0290 ; r24 = bufferA[3] out 0x05, r24 ; PORTB = r24 lds r24, 0x0291 ; r24 = bufferA[4] sts 0x0108, r24 ; PORTK = r24 lds r24, 0x0292 ; r24 = bufferA[5] out 0x11, r24 ; PORTF = r24 lds r24, 0x0293 ; r24 = bufferA[6] sts 0x0102, r24 ; PORTH = r24 lds r24, 0x0294 ; r24 = bufferA[7] out 0x0b, r24 ; PORTD = r24 lds r24, 0x0295 ; r24 = bufferA[8] out 0x14, r24 ; PORTG = r24 lds r24, 0x0296 ; r24 = bufferA[9] sts 0x0105, r24 ; PORTJ = r24 </code></pre> <p>The <code>out</code> instruction is still single cycle, but <code>lds</code> (load from memory) and <code>sts</code> (store to memory) take two cycles each. You may notice that only ports A through F are accessed with the <code>out</code> instruction. This is because they are mapped in the I/O address space of the microcontroller. The other four ports are accessed using the slower <code>sts</code> instruction on memory-mapped addresses.</p> <p>If you count your cycles, you should get 34 cycles for the whole sequence, which is 2.125 µs at 16 MHz. Ideally, you would like this to take 2.5 µs (1/10 of a cycle of a 40 kHz signal). You may notice that the code you took inspiration from has a few instructions between successive calls to <code>OUTPUT_WAVE()</code>. It looks to me like those were carefully timed to get as close as possible to 2.5 µs per phase. This approach is obviously fragile: any tiny change in the code, or even a compiler upgrade, can throw off your carefully timed code.</p> <p><strong>Edit</strong>: The second question, if I understand it correctly, is about the change in duty cycle. The waveforms have a <em>nominal</em> duty cycle of 50%: the signal is LOW over 5 time slots (5/10 of the cycle), then HIGH for the next 5 time slots. The time slots, however, do not have all the same length. The first nine last 2.125 µs each. The last one, however, is somewhat longer, because it takes the duration of the code handling the serial port, and the two cycles of <code>goto LOOP;</code>. If the longer time slot happens when the output is HIGH, you get an actual duty cycle higher than 50%. If it happens when it is HIGH, you get a shorter duty cycle, like in your “shift wave failed” example.</p>
91487
|serial|esp8266|uart|
ESP8266 module doesn't respond to commands and sends garbage to serial on boot
2022-12-01T18:16:22.047
<p>I bought a ESP8266 module (like <a href="https://rads.stackoverflow.com/amzn/click/com/B00O34AGSU" rel="nofollow noreferrer" rel="nofollow noreferrer">this</a>). I connected the module like on the following scheme: <a href="https://i.stack.imgur.com/tJDBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tJDBx.png" alt="scheme" /></a></p> <p>I use a USB to TTL converter (cp2102) that I've connected to RX&amp;TX pins of the module. It works. It successfully transmits data in both ways when I test it with a MCU. I often use it to send debug messages to my PC from a MCU.</p> <p>I use linux and CuteCom as a program for monitoring the data sent through the serial port.</p> <p>I supply 3.3V to the module (as required by the manufacturer) from the cp2102 converter (it has both 5V and 3.3V outputs).</p> <p><strong>The problem</strong></p> <p>The module does not respond to any command I send to it (AT, AT+GMR, AT+RST, ATE0, etc). But it sends to the PC some data on boot (when I attach Vcc to CP_PD). Most of the data look like garbage, but at the very end I get meaningful data:</p> <pre><code>Ai-Thinker Technology Co.,Ltd. invalid </code></pre> <p>The baud rate is 115200. No parity, 8-bit characters, 1 stop bit. The full output from CuteCom: <a href="https://i.stack.imgur.com/rc8VT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rc8VT.png" alt="data" /></a></p> <p>The red LED on the module is always lightning while the power is supplied. During the boot process (approximately first 500 milliseconds) also a blue LED blinks a few times (probably due to sending that mostly-garbage data to the PC I mentioned earlier).</p> <p><strong>What have I tried?</strong></p> <p>I experimented with the resistor R1, tried: no resistor, 1k, 3k, 10k. I also tried other baud rates (1200, 2400, 4800, 9600, 19200, 38400, 57600). And tried using all the parity types, 2 stop bits and other character lengths. Nothing helped.</p> <p>Why the module does not respond to any command? Hope for your help! Thanks in advance!</p>
<p>The <a href="https://docs.espressif.com/projects/esptool/en/latest/esp8266/esptool/serial-connection.html" rel="nofollow noreferrer">ESP8266 bootloader outputs messages at that 74880 bits per second</a>. At other speeds the bootloader's messages will look like garbage. Set your terminal speed to 74880 to see them.</p> <p>On the ESP8266 it can be helpful to also use 74880 bits per second for the <code>Serial</code> speed in your program so that you can easily see both your programs output and the boot loader information when your program crashes.</p>
91490
|esp8266|uart|reset|
How to reset flow control that prevents me from reading data from ESP8266?
2022-12-01T21:53:19.580
<p>I have a ESP8266 module (like <a href="https://i.stack.imgur.com/Djlet.png" rel="nofollow noreferrer">this</a>). I ran a command <code>AT+UART_DEF=115200,8,1,0,3</code> as mentioned in documentation of ESP8266 SDK to change the baud rate of my ESP8266 module. It seems like by running this command I bricked my ESP because now the module does not respond to any command (tried 9600, 74880, 115200 baud rates) and all the data that is sent after the bootloader messages on 74880 baud rate is garbage. The last argument of the above command sets the flow control to &quot;both RTS and CTS&quot; (3), but I don't have those pins. The module's pinout:</p> <p><a href="https://i.stack.imgur.com/Djlet.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Djlet.png" alt="pinout" /></a></p> <p>So I suppose on my ESP I can't use hardware flow control. (Or I can?)</p> <p>I still can receive bootloader's message that is sent on boot on baud rate 74880 bps:</p> <pre><code>ets Jan 8 2013,rst cause:1, boot mode:(3,6) load 0x40100000, len 6960, room 16 tail 0 chksum 0x4f load 0x3ffe8008, len 24, room 8 tail 0 chksum 0xc6 load 0x3ffe8020, len 3196, room 8 tail 4 chksum 0x3a csum 0x3a user code done </code></pre> <p>But all the data that is sent after the bootloader is garbage: <a href="https://i.stack.imgur.com/L2vV9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L2vV9.png" alt="data" /></a></p> <p>To clarify, before running the <code>AT+UART_DEF</code> command I could receive meaningful data and execute commands on baud rate 115200 bps.</p> <p>I'm not sure if the command I ran is the problem, so please point me out if I'm wrong. As per documentation:</p> <pre><code>The configuration changes will be saved in the NVS area, and will still be valid when the chip is powered on again. </code></pre> <p>The new UART settings along with the flow control settings are stored in NVS area. Is it possible to reset it? Or any other way to reset the flow control?</p> <p><strong>What have I tried?</strong></p> <p>I tried to erase all the flash memory of the module using <code>esptool</code>: <code>erase_region 0x0 0x1000000</code> and then tried to flash the latest AT firmware again. Didn't help. It still receives bootloader messages and some garbage data.</p> <p>How can I unbrick my ESP? Hope for your help! Thanks in advance!</p>
<p>You can't brick an ESP8266 through software.</p> <p>You can confirm this by flashing a different, very simple program to it, like this:</p> <pre><code>#include &lt;Arduino.h&gt; void setup() { Serial.begin(74880); delay(1000); Serial.println(&quot;hello world&quot;); } loop() { } </code></pre> <p>With the serial monitor set to 74880 bits per second, you should see the bootloader messages as well as a single line of &quot;hello world&quot;.</p> <p>You also should completely erase the contents of the flash chip, not just a particular region.</p> <pre><code>esptool.py erase_flash </code></pre> <p>Afterwards you'll need to reinstall the firmware you were trying to run.</p>
91495
|esp8266|wifi|battery|
Slow WiFi reconnection after deep sleep (6 to 10 seconds)
2022-12-02T12:53:35.210
<p>With my ESP8266, I need to make a simple GET request to a server, and then go to deep sleep (the goal is 1 year battery powered)... until a signal comes on <code>RST</code> and then it starts again.</p> <p>The following code works, but <strong>it takes 6 to 10 seconds on each <code>RST</code> to get connected to my home WiFi using &quot;WPA2 Personal&quot;</strong> (when it stops blinking in my code).</p> <p><strong>Is this 6 to 10 seconds delay normal, do you have the same order of magnitude?</strong> Or can we go down to 1 second, after a wake-up from deep sleep?</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;WiFiClient.h&gt; #include &lt;ESP8266HTTPClient.h&gt; WiFiClient client; HTTPClient http; void setup() { pinMode(LED_BUILTIN, OUTPUT); if (WiFi.SSID() != WIFI_SSID) { // don't do begin if not necessary, see tutorial link after WiFi.begin(&quot;MySSID&quot;, &quot;MyPassword&quot;); WiFi.persistent(true); WiFi.setAutoConnect(true); WiFi.setAutoReconnect(true); } while(WiFi.status() != WL_CONNECTED) { digitalWrite(LED_BUILTIN, LOW); delay(10); digitalWrite(LED_BUILTIN, HIGH); delay(200); // blinking } http.begin(client, &quot;http://example.com/request.php&quot;); http.GET(); http.end(); digitalWrite(LED_BUILTIN, LOW); delay(500); digitalWrite(LED_BUILTIN, HIGH); delay(500); ESP.deepSleep(0); } void loop() { } </code></pre> <p>Note: I have read and carefully respected this useful information about low power / battery-powered ESP8266:<br /> <a href="https://github.com/z2amiller/sensorboard/blob/master/PowerSaving.md" rel="nofollow noreferrer">Power Saving tips for the ESP8266</a> (especially this <a href="https://github.com/z2amiller/sensorboard/blob/master/PowerSaving.md#do-not-call-wifibegin-in-setup" rel="nofollow noreferrer">paragraph</a>):</p> <blockquote> <p>Do not call WiFi.begin() in setup().<br /> The ESP8266 chip saves the last known wifi settings. Calling WiFi.begin() wipes those out. By calling WiFi.begin() only when it was needed, I shaved more than 2 seconds from the average amount of time it takes to associate with the AP. WiFi.begin() should be called only if the saved SSID does not match the configured SSID. You can check the configured SSID with the WiFi.SSID() call. Also, it is good practice to clear the saved WiFi settings if the timer expires. (See next section &quot;Use watchdog timers&quot;)</p> </blockquote>
<p>It is in general take around 6s for the ESP to scan all the 2.4GHz Wi-Fi channels to find the SSID and the associated BSSID (i.e. Mac Address), you can eliminate the scanning time by connecting using BSSID.</p> <p>Using a static IP instead of rely on DHCP server to assign an IP would further reduce the WiFi connecting time by another 500ms.</p> <p>See one of my <a href="https://www.e-tinkers.com/2022/04/esp8266-ntp-clock-with-ntp-update-and-charlieplexing/" rel="nofollow noreferrer">project</a> (under the &quot;ESP8266 WiFi - How to speed up connection&quot; section) where I cut the connection time from 6s down to about 2s.</p> <p>Code signature for WiFi.begin with BSSID <a href="https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.h#L38-L39" rel="nofollow noreferrer">here</a>:</p> <pre><code> const byte WIFI_BSSID[] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC}; WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 0, WIFI_BSSID); </code></pre> <p>For calculating IoT battery consultion, use <a href="https://www.of-things.de/battery-life-calculator.php" rel="nofollow noreferrer">IoT battery life calculator</a>.</p>
91503
|esp8266|
How do I wake the ESP8266 from deep sleep on a specific date and time?
2022-12-02T16:09:27.667
<p>I'd like to put my ESP8266 into deep sleep and then wake it up at at specific date and time, [roughly] to the second.</p> <p>Edit: Unfortunately, ESP8266 deep sleep doesn't support values greater than about 3.5 hours. I tried sleeping for an hour at a time until the desired time is reached, but found that it's not very accurate; often dozens seconds of drift on each wake, adding up to many minutes of drift after several hours.</p> <p>Edit: I want to wake every 24 hours at a specific time. A few seconds per week drift is more than acceptable, as I'll be re-syncing the clock every 24 hours or so.</p> <p>Edit: I'm using <code>WAKE_RF_DISABLED</code> to disable WiFi to save power on wake, so when it wakes up, there is usually no internet connection to check the time (I want to connect to WiFi only once every 24h).</p>
<p>Since the ESP8266 doesn't have a <em><a href="https://nodemcu.readthedocs.io/en/dev/modules/rtctime/" rel="nofollow noreferrer">real</a></em> onboard RTC (i.e. it's not capable of keeping very accurate time while in deep sleep) and is limited to a <a href="https://nodemcu.readthedocs.io/en/dev/modules/rtctime/#rtctimedsleep" rel="nofollow noreferrer">short time period</a>, one solution is to use an external RTC (real time clock) but there is a way of doing it without.</p> <p>Below are 3 approaches, the first two involve a <a href="https://datasheets.maximintegrated.com/en/ds/DS3231.pdf" rel="nofollow noreferrer">DS3231</a> RTC (quite easy to get as a module). For low power, I prefer DS3231 over DS1307, since DS3231 modules seem to work fine at 2.6V (whereas DS1307 modules seem to require at least 3.3V... or more like 4.5V according to the <a href="https://datasheets.maximintegrated.com/en/ds/DS1307.pdf" rel="nofollow noreferrer">datasheet</a>). The 3rd approach is useful if you don't want to add an external RTC.</p> <blockquote> <p>&quot;The DS3231 is a low-cost, extremely accurate I2C real-time clock (RTC)&quot;. The DS3231 &quot;maintains the RTC to within ±2 minutes per year accuracy from -40°C to +85°C&quot;</p> </blockquote> <p><strong>Solution 1: Periodically wake the MCU and check the external RTC</strong></p> <p>Probably, the most energy efficient solution (compared to using the alarm solution below) would be to wake the ESP8266 from deep sleep periodically to check the time on the external RTC and depending on desired accuracy, deep sleep for shorter periods as you approach the target wake time (e.g. wake and check the RTC every minute once you're about 10 mins away from the target time).</p> <p>To save power, before sleeping the ESP8266, you can simply use a transistor connected to GPIO to turn off the Vcc power supply on the DS3231 module (it'll use the onboard 2032 battery while no power is supplied). Don't forget to turn off the I2C pull-ups too, as they can provide parasite power to the RTC. You can also just disconnect GND.</p> <p>If restarted with WiFi off (<code>ESP.deepSleep(1e6, WAKE_RF_DISABLED)</code>), the ESP8266 only needs to wake for about 200 ms consuming 20 mA to check the DS3231 if it's time to wake up fully. This is probably the most energy efficient you can get with wanting to keep accurate time.</p> <p><strong>Solution 2: Set an alarm on the external RTC to wake the MCU</strong></p> <p>Using the DS3231, the SQW pin can be connected to the ESP8266 RST pin via a <a href="https://electronics.stackexchange.com/a/644782/288848">monostable circuit</a>. The monostable circuit is important because the RST pin can't stay low, as it won't boot. The monostable circuit creates a pulse on the RST pin when the DS3231 SQW pin goes low.</p> <p>A note on power consumption: The ESP8266 should consume only 20 µA in deep sleep, but DS3231 modules actually tend to use about <strong>1 mA</strong> when powered on (which is required to trigger the alarm), probably because of the EEPROM on the module. That power consumption is significant if you're designing a low power system. This is why this 2nd solution is less energy efficient compared to the 1st solution.</p> <p>The following code will set an alarm to a specific time, and when the RST pin is pulled low (based on the SQW output of the DS3231), the ESP8266 then wakes up. Make sure you uncomment <code>SLEEP_DT</code> and set a date and time to wake at a specific date and time (of course, you can set this programmatically to any date and time), otherwise it'll wake up every <em>n</em> seconds (value of <code>SLEEP_SECONDS</code>) but that might also be useful (ESP8266 deep sleep time isn't very accurate).</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; // TODO: NTPClient is redundant; replace with native // ESP8266 NTP functions (configTime and localtime) #include &lt;NTPClient.h&gt; #include &lt;WiFiUdp.h&gt; #include &lt;RTClib.h&gt; #define WIFI_SSID &quot;Your WiFi SSID&quot; #define WIFI_PASS &quot;Your WiFi password&quot; // uncomment to wake up at specific date and time //#define SLEEP_DT #define SLEEP_DT_YEAR 2022 #define SLEEP_DT_MONTH 12 #define SLEEP_DT_DAY 02 #define SLEEP_DT_HOUR 15 #define SLEEP_DT_MINUTE 50 #define SLEEP_DT_SECOND 25 #define SLEEP_SECONDS 10 // easier for testing RTC_DS3231 rtc; WiFiUDP udp; NTPClient ntp(udp); void print_date(const DateTime&amp; dt); void setup() { Serial.begin(9600); while (!Serial) { delay(1); } Serial.println('\n'); Serial.println(&quot;Hello RTC wake deep sleep&quot;); Serial.println(&quot;Init DS3231&quot;); if(!rtc.begin()) { Serial.println(&quot;DS3231 failed&quot;); while (true) { delay(1); } } // not needed rtc.disable32K(); // not used rtc.disableAlarm(2); // apparently can lead to problems if not cleared rtc.clearAlarm(1); rtc.clearAlarm(2); // stop oscillating; allows alarm to work rtc.writeSqwPinMode(DS3231_OFF); Serial.println(&quot;Init WiFi&quot;); WiFi.begin(WIFI_SSID, WIFI_PASS); Serial.println(&quot;Connecting to &quot; WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { delay(100); } Serial.print(&quot;Connected, IP: &quot;); Serial.println(WiFi.localIP()); ntp.begin(); bool ntpOk = ntp.update(); if (rtc.lostPower()) { Serial.println(&quot;RTC lost power, setting time&quot;); if (ntpOk) { Serial.println(&quot;Using time from NTP client&quot;); rtc.adjust(DateTime(ntp.getEpochTime())); } else { // untested code Serial.println(&quot;NTP unavailable, using time of build&quot;); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } } Serial.print(&quot;Date and time set to: &quot;); print_datetime(rtc.now()); #ifdef SLEEP_DT DateTime alarm( SLEEP_DT_YEAR, SLEEP_DT_MONTH, SLEEP_DT_DAY, SLEEP_DT_HOUR, SLEEP_DT_MINUTE, SLEEP_DT_SECOND); Serial.print(&quot;Setting alarm for date: &quot;); print_datetime(alarm); if (!rtc.setAlarm1(alarm, DS3231_A1_Date)) { Serial.println(&quot;Failed to set alarm&quot;); } #else // sleep for set seconds for the purposes of testing Serial.print(&quot;Setting alarm for seconds: &quot;); Serial.print(SLEEP_SECONDS); Serial.println(&quot; seconds&quot;); if (!rtc.setAlarm1(rtc.now() + TimeSpan(SLEEP_SECONDS), DS3231_A1_Second)) { Serial.println(&quot;Failed to set alarm&quot;); } #endif // SLEEP_DT Serial.println(&quot;Going into deep sleep (wake on RST low)&quot;); Serial.flush(); ESP.deepSleep(0); } void print_datetime(const DateTime&amp; dt) { char df[] = &quot;YYYY-MM-DD hh:mm:ss&quot;; Serial.println(dt.toString(df)); } void loop() { } </code></pre> <p>Here it is in action...</p> <p><a href="https://i.stack.imgur.com/fYn3g.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fYn3g.gif" alt="Arduino IDE and output" /></a></p> <p>Note: The time jumps because I chopped out a few frames to save you from being bored (no smoke and mirrors, I promise).</p> <p><strong>Solution 3: Use only the internal RTC</strong></p> <p>Keeping with the low power theme: to use the internal RTC in deep sleep, you have to keep sleeping for <em>n</em> seconds until desired seconds elapse. You can keep track of how many seconds have elapsed by using the RTC memory. This approach allows you to implement time keeping without having to add an external RTC, and without having to reconnect connect to WiFi every hour. However, I have found the drift to be quite substantial (many seconds per hour), so this is probably useful only when accuracy is not a major concern.</p>
91505
|serial|motor|communication|python|serial-data|
What is the best (fastest and most robust) way to send messages back and forth between Python on a PC and an Arduino, over serial?
2022-12-02T17:07:21.803
<p>I am trying to communicate between a PC running Python using PySerial and an Arduino. The Arduino itself has a CAN shield, and is responsible for interfacing with a motor. My goal is for the PC to construct the desired CAN frame (8 bytes), send it over Serial to the Arduino, which then itself uses a CAN library to speak to the motor. The motor then send a return frame of the same size, which the Arduino copies to an array, and also prints it to serial.</p> <p>This works in some cases, although I'm struggling to make it robust. As an example, I am driving the motor in torque control mode (Command 37 in <a href="https://cdn.robotshop.com/media/m/mya/rbc-mya-04/pdf/rmd_servo_motor_control_protocol.pdf" rel="nofollow noreferrer">this datasheet</a>). For an arbitrary forward torque of '50', the sending frame should be:</p> <pre><code>[161, 0, 0, 0, 50, 0, 0, 0] </code></pre> <p>And for a command of '-50', the frame should be:</p> <pre><code>[161, 0, 0, 0, 206, 255, 255, 255] </code></pre> <p>I didn't appreciate this would be an issue, but my guess is that because this actually requires more characters, it takes longer to send. Positive torque commands are sent with no issues, while the negative ones cause the motor to skip or judder. I can see that the Arduino isn't actually receiving the correct command at times, see below (left is sent frame from Python, and right is what the Arduino receives printed straight back).</p> <p><a href="https://i.stack.imgur.com/SeQos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SeQos.png" alt="Left is desired and sent frame, right is what the Arduino gets." /></a></p> <p>I have tried:</p> <ol> <li>Flushing serial buffers before and after sending messages, on both devices</li> <li>Adding delays to try and slow the communication down</li> <li>Changing baudrates</li> <li>Trying to use Serial.write() instead of Serial.print() as I assumed it might be faster (?)</li> </ol> <p>I have attached my code below, but in general, <em><strong>what is the best way to communicate over serial between Python and Arduino, robustly and quickly? Even if my current application is ignored, what might ideal scripts for each look like?</strong></em></p> <p>Python:</p> <pre><code> def serial_begin(self, baud, com): self.ser = serial.Serial(com, baud) self.ser.flushInput() self.ser.flushOutput() print(&quot;Connected to Serial Port &quot; + com) t.sleep(1) def send_cam_frame(self, frame): self.send_frame = frame string_to_send = &quot;&lt;&quot; + str(int(frame[0])) + &quot;,&quot; + \ str(int(frame[1])) + &quot;,&quot; + \ str(int(frame[2])) + &quot;,&quot; + \ str(int(frame[3])) + &quot;,&quot; + \ str(int(frame[4])) + &quot;,&quot; + \ str(int(frame[5])) + &quot;,&quot; + \ str(int(frame[6])) + &quot;,&quot; + \ str(int(frame[7])) + &quot;&gt;&quot; self.ser.write(string_to_send.encode('UTF-8')) self.receive_can_frame() def receive_can_frame(self): get_data = self.ser.readline().decode('UTF-8', errors='ignore')[0:][:-2] self.receive_frame = np.fromstring(get_data, dtype='int', count=8, sep=' ') def set_torque(self, torque): self.command = self.command_list[&quot;SET_TORQUE&quot;] torque = int(self.constrain(torque * 2000 / 32, -2000, 2000)) frame = [self.command, 0, 0, 0, torque &amp; 0xFF, (torque &gt;&gt; 8) &amp; 0xFF, (torque &gt;&gt; 16) &amp; 0xFF, (torque &gt;&gt; 24) &amp; 0xFF] self.send_cam_frame(frame) def main(): arduino_port = &quot;COM5&quot; # Default COM port baud_rate = 57600 # Default Baud Rate rmd = Motor() rmd.serial_begin(baud=baud_rate, com=arduino_port) set_torque = 0 while True: try: if keyboard.is_pressed('w'): set_torque += 0.001 if keyboard.is_pressed('s'): set_torque -= 0.001 rmd.set_torque(set_torque) except KeyboardInterrupt: rmd.disable_motor() print(&quot;Keyboard Interrupt&quot;) </code></pre> <p>Arduino:</p> <pre><code> byte recvFrame[8] = {0, 0, 0, 0, 0, 0, 0, 0}; byte sendFrame[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // Serial Read Parameters const byte numChars = 32; // Length of received char array from Serial char receivedChars[numChars]; // Received char array from Serial char tempChars[numChars]; // Temporary array for use when parsing bool newData = false; // Flag to check if newData has been received void setup() { Serial.begin(57600); delay(1000); } void loop() { CANMessage frame; frame.id = 0x140 + 1; frame.len = 8; // Do not touch this section recvWithStartEndMarkers(); // Check Serial and receive data if there is newData if (newData == true) { strcpy(tempChars, receivedChars); // Copy variables to prevent them being altered parseData(); // Parse data (split where there are commas) for (int i = 0; i &lt; 8; i++){ frame.data[i] = sendFrame[i]; } can.tryToSend(frame); newData = false; // Set to false } if (can.available()){ can.receive(frame); } for (int i = 0; i &lt; 8; i++){ recvFrame[i] = frame.data[i]; } printFrame(); } // Do not touch this function void recvWithStartEndMarkers() { static boolean recvInProgress = false; static byte ndx = 0; char startMarker = '&lt;'; char endMarker = '&gt;'; char rc; while (Serial.available() &gt; 0 &amp;&amp; newData == false) { rc = Serial.read(); if (recvInProgress == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx &gt;= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string recvInProgress = false; ndx = 0; newData = true; } } else if (rc == startMarker) { recvInProgress = true; } } } // Only touch this function if more data is being sent from Python code void parseData() { // split the data into its parts char * strtokIndx; // this is used by strtok() as an index strtokIndx = strtok(tempChars,&quot;,&quot;); sendFrame[0] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[1] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[2] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[3] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[4] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[5] = atoi(strtokIndx); strtokIndx = strtok(NULL,&quot;,&quot;); sendFrame[6] = atoi(strtokIndx); strtokIndx = strtok(NULL, &quot;,&quot;); sendFrame[7] = atoi(strtokIndx); // How to add a new variable // Currently, data is sent as &lt;0, 0, 0, 0&gt; // If a fourth parameter was to be sent (&lt;0, 0, 0, 0, 1&gt;), the following lines need to be added // strtokIndx = strtok(NULL, &quot;, &quot;); This reads the string, from where it was previously cut, up until the next comma // newVariableName = atoi(strtokIndx); atoi is 'to integer'. If newVariable is a float, atof is needed etc } void printFrame(){ for (int i = 0; i &lt; 8; i++){ Serial.print(sendFrame[i]); Serial.print(&quot; &quot;); } Serial.println(); //Serial.write(sendFrame, 8); //delay(3); } </code></pre> <p>N.B: I have removed some of the unnecessary functions from both scripts (e.g: the rest of the Motor class for the Python, and the CAN Shield setup from the Arduino) for clarity.</p>
<p>There is no best way, but there is a better way (and more efficient way).</p> <blockquote> <p>For an arbitrary forward torque of '50', the sending frame should be:</p> <p>[161, 0, 0, 0, 50, 0, 0, 0]</p> <p>And for a command of '-50', the frame should be:</p> <p>[161, 0, 0, 0, 206, 255, 255, 255]</p> </blockquote> <p>Most of the programmers who are new to embedded program, prepare their data to be send via communication as string instead of sending raw binary data, the problem is that</p> <ol> <li>to send a value of 215, you are sending 3 bytes of ASCII('2', '1', '5') while the data can actually sent by one single byte.</li> <li>both integer 256 (<code>0x0100</code>) and 32766 (<code>0x7FFE</code>) only took up two bytes, but when you encode it as ASCII, you are dealing with various length from 3 chars to 5 chars. This not only take more bytes to send the data but also make parsing of the data more difficult unless you had some delimiter to separate the data, e.g. (&quot;256,32766&quot; separated by comma).</li> </ol> <p>Looking at your data set and datasheet, it is clear that the each data point is represented by a 4-byte signed data with small <a href="https://en.wikipedia.org/wiki/Endianness" rel="nofollow noreferrer">endian</a> (i.e. the lower byte get send first), so decimal <code>50</code> is <code>0x00000032</code>, it is store in memory as <code>0x32, 0x00, 0x00, 0x00</code> with small endian.</p> <p>A negative value is represented in <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">two's compliment</a> of the positive value, so <code>-50</code> in decimal is <code>0xFFFFFFCE</code> and stored as <code>0xCE, 0xFF, 0xFF, 0xFF</code>.</p> <p>In python, the <a href="https://docs.python.org/3/library/struct.html" rel="nofollow noreferrer">struct</a> library allows you to converts between Python values and C structs represented as Python bytes objects.</p> <pre class="lang-python prettyprint-override"><code>form struct import * torque = -50 data = pack('&lt;i', torque) # pack torque as a 4-byte integer with little endian ser.write(torque) # send over serial as bytes </code></pre> <p>On the Arduino side, read the data from Serial as <code>byte</code>(i.e. <code>uint8_t</code>) and store it in an array. You can then convert it back to a <code>int32</code>.</p> <pre class="lang-cpp prettyprint-override"><code>// assuming you had read these 4 bytes of data from Serial and add them into an array uint8_t data[4]{0xCE, 0xFF, 0xFF, 0xFF}; // Convert received data bytes to int32_t int32_t torque = static_cast&lt;int32_t&gt; (data[3]&lt;&lt; 24 | data[2] &lt;&lt; 16 | data[1] &lt;&lt; 8 | data[0]); // This will return result of -50 Serial.println(torque); </code></pre> <p>This should reduce the code and improve the efficiency of the sending the data significantly.</p> <p>The code along however does not improve the reliability, one advantage of sending data as string is that you could determine the end of data stream by detecting the <code>\0</code> terminator at end of the string. When sending raw binary, ideally you need to have the mechanism to signify the number of bytes the data of bytes that you are going to send over.</p>
91520
|arduino-ide|attiny|electronics|attiny85|
Need help ATtiny85 not working as standalone
2022-12-03T23:32:08.567
<p>I have ATTiny85 that I want to drive a servo. Burned bootloader to the ATTiny85 and I am using HW-260 development board to program and to test the code. While the ATTiny85 works perfectly on the HW-260 development board, I cant get it to work as a standalone on a breadboard when testing with the servo by using the Adafruit_SoftServo library and with the blink example. Tried adding 4.7kOhm pull-up resistor to PB5 to prevent the ATTiny85 from resetting but I get the same result. Tried powering the standalone layout with 3V coin cell, USB 5V, powerbank 5V and nothing. This is the servo code I am using:</p> <pre><code>Adafruit_SoftServo myservo; int pos = 0; void setup() { myservo.attach(PB0); } void loop() { for (pos = 0; pos &lt;= 180; pos += 1) { myservo.write(pos); myservo.refresh(); delay(15); } for (pos = 180; pos &gt;= 0; pos -= 1) { myservo.write(pos); myservo.refresh(); delay(15); } } </code></pre> <p>The blink code I am using is from the examples, I just change the output pin as PB1. If I connect the PB5 briefly to ground, I get the servo to turn a bit in random direction. Measured and the breadboard is not the problem, everything seems to be connected correctly.</p> <p>This is the bootloader I used <a href="https://github.com/ashishchoudhary9998/ATtiny85-Boot-loader" rel="nofollow noreferrer">https://github.com/ashishchoudhary9998/ATtiny85-Boot-loader</a></p> <p><strong>Edit:</strong> This is the schematic of the HW-260 board <a href="https://i.stack.imgur.com/iujqu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iujqu.png" alt="enter image description here" /></a></p> <p>This is my layout <a href="https://i.stack.imgur.com/K2nIH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K2nIH.png" alt="enter image description here" /></a></p>
<p>After adding the schematics, a difference can be spotted:</p> <p>PB3 needs a pull-up, on the development board it has 1,5 kΩ. This resistor is part of the <a href="https://en.wikipedia.org/wiki/USB_(Communications)#Line_transition_state" rel="nofollow noreferrer">USB standard</a> and signals &quot;low speed device&quot;. Presumably (because the source of it is not provided) the bootloader needs this to start at all, too.</p> <p>The delay mentioned in a comment is typical for ATtiny85 development. Because of the low number of pins, the bootloader starts and waits for some seconds for a PC to connect. If no connection is established, the user program is started. It can then use all pins for its own purposes.</p>
91525
|variables|
IsTimeSet library - Assign variables
2022-12-04T15:34:01.367
<p>i get the current time with the example code istimneforset, everything works fine.</p> <p>now i want to get the current time from the function &quot;Serial.println(timeClient.getFormattedTime());&quot; and i am trying to cache the first character of the array.</p> <p>code:</p> <pre><code>#include &lt;NTPClient.h&gt; // Change the next line to use with a different map/shield #include &lt;ESP8266WiFi.h&gt; //#include &lt;WiFi.h&gt; // for WiFi shield //#include &lt;WiFi101.h&gt; // for WiFi 101 shield or MKR1000 #include &lt;WiFiUdp.h&gt; const char *ssid =&quot; *&quot;; const char *password = &quot;*&quot;; WiFiUDP ntpUDP; // initialized to a time offset of 10 hours NTPClient timeClient(ntpUDP, &quot;pool.ntp.org&quot;, 36000, 60000); // HH:MM:SS // timeClient is initialized to 10:00:00 if it does not receive an NTP packet // before the timeout of 100ms is received. // Without isTimeSet(), the LED would be lit even though the time was // was not yet set correctly. const int hour = 10; const int minute = 0; void setup(){ Serial.begin(9600); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay (500); Serial.print(&quot;.&quot;); } timeClient.begin(); } void loop() { timeClient.update(); //Serial.println(timeClient.getFormattedTime()); int stund2 = (timeClient.getFormattedTime()[0]); Serial.println(stund2); } </code></pre> <p>unfortunately it always gives me a wrong value. my goal is to have the current hour in a variable. can someone help me? thanks!</p>
<p>While st2000 gave a good answer about how to do it instead, I wanted to explain what actually went wrong with your first solution.</p> <p>You are seeing the difference between binary and ASCII encoded data. Using <code>timeClient.getFormattedTime()</code> will give you an ASCII encoded string. Such a string is an array of <code>char</code>s, each one representing one character (according to the ASCII table) until the string gets terminated with the null character <code>\0</code>.</p> <p>You are taking the first character and assign it to an integer variable. The value will be directly copied into that variable. But the first element in that <code>char</code> array is the ASCII digit <code>0</code>, which is the equivalent of decimal <code>48</code>. And that is what you get from your code. Also the hour field of that string is 2 characters wide, so you need to read both of them, not just the first character.</p> <p>If you want to extract numbers from a string, you cannot just assign them. You need to parse the data correctly. For that you would tokenize the string (split it in individual parts with data) (for example with <code>strtok()</code>) and then parse each token with a corresponding function. To parse an integer value from a string you can use <code>atoi()</code>. This function will read the string, until a non-digit character appears, and convert that to an integer.</p> <p>So - since we are only interested into the first number/token in that string, you can leave out the tokenizing and just parse that string (since after the number of hours there is always the <code>:</code> character, which is a non-digit character):</p> <pre><code>int stund2 = atoi(timeClient.getFormattedTime()); </code></pre> <p>I have not tested this, but it should also work, though not that efficient as the solution of st2000, since parsing string data is commonly more complex than working directly with integer numbers.</p>
91542
|esp8266|time|
What is the ideal way to check if time on ESP8266 via NTP is ready?
2022-12-05T20:38:01.877
<p>With ESP8266, I noticed that for the first 1 or 2 loops, <code>localtime</code> returns Unix epoch (1970 date) until it has finished getting the actual time from NTP, after which point I see the real date. Sometimes it can take 10 seconds or so before NTP is available, depending on what time server I use and how frequently I make requests to it (most time servers have request throttling, it seems).</p> <p>Right now, I'm checking whether the date is valid by testing if the year is <code>70</code> but this seems weird and hacky. Is there a better way? For instance, is there a function that returns <code>true</code> if the NTP update has been successful or <code>-1</code> if not?</p> <p>All of the examples of <code>localtime</code> that I have found so far don't seem to check if the date is valid, and if I run their code, it almost always prints the 1970 Unix epoch date on the first loop.</p> <pre><code>#define TIME_SERVER_1 &quot;time.google.com&quot; #define TIME_SERVER_2 &quot;time.nist.gov&quot; #define TIME_SERVER_3 &quot;pool.ntp.org&quot; #define TIMEZONE TZ_Europe_London void setup() { // .. configTime(TIMEZONE, TIME_SERVER_1, TIME_SERVER_2, TIME_SERVER_3); // .. } void loop() { // .. time_t now; time(&amp;now); struct tm* timeinfo = localtime(&amp;now); // TODO: maybe there's a better way to check unknown time? if (timeinfo-&gt;tm_year == 70) { TRACE_LN(F(&quot;ntp not yet available&quot;)); } else { epoch = mktime(timeinfo); } //.. } </code></pre>
<p><strong>Continuation of timezones:</strong></p> <pre><code> {&quot;TZ_America_Santarem &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_America_Santiago &quot;,&quot;&lt;-04&gt;4&lt;-03&gt;,M9.1.6/24,M4.1.6/24&quot;}, {&quot;TZ_America_Santo_Domingo &quot;,&quot;AST4&quot;}, {&quot;TZ_America_Sao_Paulo &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_America_Scoresbysund &quot;,&quot;&lt;-01&gt;1&lt;+00&gt;,M3.5.0/0,M10.5.0/1&quot;}, {&quot;TZ_America_Sitka &quot;,&quot;AKST9AKDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_St_Barthelemy &quot;,&quot;AST4&quot;}, {&quot;TZ_America_St_Johns &quot;,&quot;NST3:30NDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_St_Kitts &quot;,&quot;AST4&quot;}, {&quot;TZ_America_St_Lucia &quot;,&quot;AST4&quot;}, {&quot;TZ_America_St_Thomas &quot;,&quot;AST4&quot;}, {&quot;TZ_America_St_Vincent &quot;,&quot;AST4&quot;}, {&quot;TZ_America_Swift_Current &quot;,&quot;CST6&quot;}, {&quot;TZ_America_Tegucigalpa &quot;,&quot;CST6&quot;}, {&quot;TZ_America_Thule &quot;,&quot;AST4ADT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Thunder_Bay &quot;,&quot;EST5EDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Tijuana &quot;,&quot;PST8PDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Toronto &quot;,&quot;EST5EDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Tortola &quot;,&quot;AST4&quot;}, {&quot;TZ_America_Vancouver &quot;,&quot;PST8PDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Whitehorse &quot;,&quot;MST7&quot;}, {&quot;TZ_America_Winnipeg &quot;,&quot;CST6CDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Yakutat &quot;,&quot;AKST9AKDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_America_Yellowknife &quot;,&quot;MST7MDT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_Antarctica_Casey &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Antarctica_Davis &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Antarctica_DumontDUrville &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Antarctica_Macquarie &quot;,&quot;AEST-10AEDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Antarctica_Mawson &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Antarctica_McMurdo &quot;,&quot;NZST-12NZDT,M9.5.0,M4.1.0/3&quot;}, {&quot;TZ_Antarctica_Palmer &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_Antarctica_Rothera &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_Antarctica_Syowa &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Antarctica_Troll &quot;,&quot;&lt;+00&gt;0&lt;+02&gt;-2,M3.5.0/1,M10.5.0/3&quot;}, {&quot;TZ_Antarctica_Vostok &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Arctic_Longyearbyen &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Asia_Aden &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Almaty &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_Amman &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Anadyr &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Asia_Aqtau &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Aqtobe &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Ashgabat &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Atyrau &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Baghdad &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Bahrain &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Baku &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Asia_Bangkok &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Barnaul &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Beirut &quot;,&quot;EET-2EEST,M3.5.0/0,M10.5.0/0&quot;}, {&quot;TZ_Asia_Bishkek &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_Brunei &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Chita &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Asia_Choibalsan &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Colombo &quot;,&quot;&lt;+0530&gt;-5:30&quot;}, {&quot;TZ_Asia_Damascus &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Dhaka &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_Dili &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Asia_Dubai &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Asia_Dushanbe &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Famagusta &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Asia_Gaza &quot;,&quot;EET-2EEST,M3.4.4/50,M10.4.4/50&quot;}, {&quot;TZ_Asia_Hebron &quot;,&quot;EET-2EEST,M3.4.4/50,M10.4.4/50&quot;}, {&quot;TZ_Asia_Ho_Chi_Minh &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Hong_Kong &quot;,&quot;HKT-8&quot;}, {&quot;TZ_Asia_Hovd &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Irkutsk &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Jakarta &quot;,&quot;WIB-7&quot;}, {&quot;TZ_Asia_Jayapura &quot;,&quot;WIT-9&quot;}, {&quot;TZ_Asia_Jerusalem &quot;,&quot;IST-2IDT,M3.4.4/26,M10.5.0&quot;}, {&quot;TZ_Asia_Kabul &quot;,&quot;&lt;+0430&gt;-4:30&quot;}, {&quot;TZ_Asia_Kamchatka &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Asia_Karachi &quot;,&quot;PKT-5&quot;}, {&quot;TZ_Asia_Kathmandu &quot;,&quot;&lt;+0545&gt;-5:45&quot;}, {&quot;TZ_Asia_Khandyga &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Asia_Kolkata &quot;,&quot;IST-5:30&quot;}, {&quot;TZ_Asia_Krasnoyarsk &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Kuala_Lumpur &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Kuching &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Kuwait &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Macau &quot;,&quot;CST-8&quot;}, {&quot;TZ_Asia_Magadan &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Asia_Makassar &quot;,&quot;WITA-8&quot;}, {&quot;TZ_Asia_Manila &quot;,&quot;PST-8&quot;}, {&quot;TZ_Asia_Muscat &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Asia_Nicosia &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Asia_Novokuznetsk &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Novosibirsk &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Omsk &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_Oral &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Phnom_Penh &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Pontianak &quot;,&quot;WIB-7&quot;}, {&quot;TZ_Asia_Pyongyang &quot;,&quot;KST-9&quot;}, {&quot;TZ_Asia_Qatar &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Qyzylorda &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Riyadh &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Asia_Sakhalin &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Asia_Samarkand &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Seoul &quot;,&quot;KST-9&quot;}, {&quot;TZ_Asia_Shanghai &quot;,&quot;CST-8&quot;}, {&quot;TZ_Asia_Singapore &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Srednekolymsk &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Asia_Taipei &quot;,&quot;CST-8&quot;}, {&quot;TZ_Asia_Tashkent &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Tbilisi &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Asia_Tehran &quot;,&quot;&lt;+0330&gt;-3:30&quot;}, {&quot;TZ_Asia_Thimphu &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_Tokyo &quot;,&quot;JST-9&quot;}, {&quot;TZ_Asia_Tomsk &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Ulaanbaatar &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Asia_Urumqi &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Asia_UstmNera &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Asia_Vientiane &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Asia_Vladivostok &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Asia_Yakutsk &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Asia_Yangon &quot;,&quot;&lt;+0630&gt;-6:30&quot;}, {&quot;TZ_Asia_Yekaterinburg &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Asia_Yerevan &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Atlantic_Azores &quot;,&quot;&lt;-01&gt;1&lt;+00&gt;,M3.5.0/0,M10.5.0/1&quot;}, {&quot;TZ_Atlantic_Bermuda &quot;,&quot;AST4ADT,M3.2.0,M11.1.0&quot;}, {&quot;TZ_Atlantic_Canary &quot;,&quot;WET0WEST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Atlantic_Cape_Verde &quot;,&quot;&lt;-01&gt;1&quot;}, {&quot;TZ_Atlantic_Faroe &quot;,&quot;WET0WEST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Atlantic_Madeira &quot;,&quot;WET0WEST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Atlantic_Reykjavik &quot;,&quot;GMT0&quot;}, {&quot;TZ_Atlantic_South_Georgia &quot;,&quot;&lt;-02&gt;2&quot;}, {&quot;TZ_Atlantic_Stanley &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_Atlantic_St_Helena &quot;,&quot;GMT0&quot;}, {&quot;TZ_Australia_Adelaide &quot;,&quot;ACST-9:30ACDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Australia_Brisbane &quot;,&quot;AEST-10&quot;}, {&quot;TZ_Australia_Broken_Hill &quot;,&quot;ACST-9:30ACDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Australia_Currie &quot;,&quot;AEST-10AEDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Australia_Darwin &quot;,&quot;ACST-9:30&quot;}, {&quot;TZ_Australia_Eucla &quot;,&quot;&lt;+0845&gt;-8:45&quot;}, {&quot;TZ_Australia_Hobart &quot;,&quot;AEST-10AEDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Australia_Lindeman &quot;,&quot;AEST-10&quot;}, {&quot;TZ_Australia_Lord_Howe &quot;,&quot;&lt;+1030&gt;-10:30&lt;+11&gt;-11,M10.1.0,M4.1.0&quot;}, {&quot;TZ_Australia_Melbourne &quot;,&quot;AEST-10AEDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Australia_Perth &quot;,&quot;AWST-8&quot;}, {&quot;TZ_Australia_Sydney &quot;,&quot;AEST-10AEDT,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Europe_Amsterdam &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Andorra &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Astrakhan &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Europe_Athens &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Belgrade &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Berlin &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Bratislava &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Brussels &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Bucharest &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Budapest &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Busingen &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Chisinau &quot;,&quot;EET-2EEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Copenhagen &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Dublin &quot;,&quot;IST-1GMT0,M10.5.0,M3.5.0/1&quot;}, {&quot;TZ_Europe_Gibraltar &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Guernsey &quot;,&quot;GMT0BST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Europe_Helsinki &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Isle_of_Man &quot;,&quot;GMT0BST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Europe_Istanbul &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Europe_Jersey &quot;,&quot;GMT0BST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Europe_Kaliningrad &quot;,&quot;EET-2&quot;}, {&quot;TZ_Europe_Kiev &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Kirov &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Europe_Lisbon &quot;,&quot;WET0WEST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Europe_Ljubljana &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_London &quot;,&quot;GMT0BST,M3.5.0/1,M10.5.0&quot;}, {&quot;TZ_Europe_Luxembourg &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Madrid &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Malta &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Mariehamn &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Minsk &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Europe_Monaco &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Moscow &quot;,&quot;MSK-3&quot;}, {&quot;TZ_Europe_Oslo &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Paris &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Podgorica &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Prague &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Riga &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Rome &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Samara &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Europe_San_Marino &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Sarajevo &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Saratov &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Europe_Simferopol &quot;,&quot;MSK-3&quot;}, {&quot;TZ_Europe_Skopje &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Sofia &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Stockholm &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Tallinn &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Tirane &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Ulyanovsk &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Europe_Uzhgorod &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Vaduz &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Vatican &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Vienna &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Vilnius &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Volgograd &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Europe_Warsaw &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Zagreb &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Europe_Zaporozhye &quot;,&quot;EET-2EEST,M3.5.0/3,M10.5.0/4&quot;}, {&quot;TZ_Europe_Zurich &quot;,&quot;CET-1CEST,M3.5.0,M10.5.0/3&quot;}, {&quot;TZ_Indian_Antananarivo &quot;,&quot;EAT-3&quot;}, {&quot;TZ_Indian_Chagos &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Indian_Christmas &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Indian_Cocos &quot;,&quot;&lt;+0630&gt;-6:30&quot;}, {&quot;TZ_Indian_Comoro &quot;,&quot;EAT-3&quot;}, {&quot;TZ_Indian_Kerguelen &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Indian_Mahe &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Indian_Maldives &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Indian_Mauritius &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Indian_Mayotte &quot;,&quot;EAT-3&quot;}, {&quot;TZ_Indian_Reunion &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Pacific_Apia &quot;,&quot;&lt;+13&gt;-13&quot;}, {&quot;TZ_Pacific_Auckland &quot;,&quot;NZST-12NZDT,M9.5.0,M4.1.0/3&quot;}, {&quot;TZ_Pacific_Bougainville &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Chatham &quot;,&quot;&lt;+1245&gt;-12:45&lt;+1345&gt;,M9.5.0/2:45,M4.1.0/3:45&quot;}, {&quot;TZ_Pacific_Chuuk &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Pacific_Easter &quot;,&quot;&lt;-06&gt;6&lt;-05&gt;,M9.1.6/22,M4.1.6/22&quot;}, {&quot;TZ_Pacific_Efate &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Enderbury &quot;,&quot;&lt;+13&gt;-13&quot;}, {&quot;TZ_Pacific_Fakaofo &quot;,&quot;&lt;+13&gt;-13&quot;}, {&quot;TZ_Pacific_Fiji &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Funafuti &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Galapagos &quot;,&quot;&lt;-06&gt;6&quot;}, {&quot;TZ_Pacific_Gambier &quot;,&quot;&lt;-09&gt;9&quot;}, {&quot;TZ_Pacific_Guadalcanal &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Guam &quot;,&quot;ChST-10&quot;}, {&quot;TZ_Pacific_Honolulu &quot;,&quot;HST10&quot;}, {&quot;TZ_Pacific_Kiritimati &quot;,&quot;&lt;+14&gt;-14&quot;}, {&quot;TZ_Pacific_Kosrae &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Kwajalein &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Majuro &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Marquesas &quot;,&quot;&lt;-0930&gt;9:30&quot;}, {&quot;TZ_Pacific_Midway &quot;,&quot;SST11&quot;}, {&quot;TZ_Pacific_Nauru &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Niue &quot;,&quot;&lt;-11&gt;11&quot;}, {&quot;TZ_Pacific_Norfolk &quot;,&quot;&lt;+11&gt;-11&lt;+12&gt;,M10.1.0,M4.1.0/3&quot;}, {&quot;TZ_Pacific_Noumea &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Pago_Pago &quot;,&quot;SST11&quot;}, {&quot;TZ_Pacific_Palau &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Pacific_Pitcairn &quot;,&quot;&lt;-08&gt;8&quot;}, {&quot;TZ_Pacific_Pohnpei &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Pacific_Port_Moresby &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Pacific_Rarotonga &quot;,&quot;&lt;-10&gt;10&quot;}, {&quot;TZ_Pacific_Saipan &quot;,&quot;ChST-10&quot;}, {&quot;TZ_Pacific_Tahiti &quot;,&quot;&lt;-10&gt;10&quot;}, {&quot;TZ_Pacific_Tarawa &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Tongatapu &quot;,&quot;&lt;+13&gt;-13&quot;}, {&quot;TZ_Pacific_Wake &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Pacific_Wallis &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Etc_GMT &quot;,&quot;GMT0&quot;}, {&quot;TZ_Etc_GMTm0 &quot;,&quot;GMT0&quot;}, {&quot;TZ_Etc_GMTm1 &quot;,&quot;&lt;+01&gt;-1&quot;}, {&quot;TZ_Etc_GMTm2 &quot;,&quot;&lt;+02&gt;-2&quot;}, {&quot;TZ_Etc_GMTm3 &quot;,&quot;&lt;+03&gt;-3&quot;}, {&quot;TZ_Etc_GMTm4 &quot;,&quot;&lt;+04&gt;-4&quot;}, {&quot;TZ_Etc_GMTm5 &quot;,&quot;&lt;+05&gt;-5&quot;}, {&quot;TZ_Etc_GMTm6 &quot;,&quot;&lt;+06&gt;-6&quot;}, {&quot;TZ_Etc_GMTm7 &quot;,&quot;&lt;+07&gt;-7&quot;}, {&quot;TZ_Etc_GMTm8 &quot;,&quot;&lt;+08&gt;-8&quot;}, {&quot;TZ_Etc_GMTm9 &quot;,&quot;&lt;+09&gt;-9&quot;}, {&quot;TZ_Etc_GMTm10 &quot;,&quot;&lt;+10&gt;-10&quot;}, {&quot;TZ_Etc_GMTm11 &quot;,&quot;&lt;+11&gt;-11&quot;}, {&quot;TZ_Etc_GMTm12 &quot;,&quot;&lt;+12&gt;-12&quot;}, {&quot;TZ_Etc_GMTm13 &quot;,&quot;&lt;+13&gt;-13&quot;}, {&quot;TZ_Etc_GMTm14 &quot;,&quot;&lt;+14&gt;-14&quot;}, {&quot;TZ_Etc_GMT0 &quot;,&quot;GMT0&quot;}, {&quot;TZ_Etc_GMTp0 &quot;,&quot;GMT0&quot;}, {&quot;TZ_Etc_GMTp1 &quot;,&quot;&lt;-01&gt;1&quot;}, {&quot;TZ_Etc_GMTp2 &quot;,&quot;&lt;-02&gt;2&quot;}, {&quot;TZ_Etc_GMTp3 &quot;,&quot;&lt;-03&gt;3&quot;}, {&quot;TZ_Etc_GMTp4 &quot;,&quot;&lt;-04&gt;4&quot;}, {&quot;TZ_Etc_GMTp5 &quot;,&quot;&lt;-05&gt;5&quot;}, {&quot;TZ_Etc_GMTp6 &quot;,&quot;&lt;-06&gt;6&quot;}, {&quot;TZ_Etc_GMTp7 &quot;,&quot;&lt;-07&gt;7&quot;}, {&quot;TZ_Etc_GMTp8 &quot;,&quot;&lt;-08&gt;8&quot;}, {&quot;TZ_Etc_GMTp9 &quot;,&quot;&lt;-09&gt;9&quot;}, {&quot;TZ_Etc_GMTp10 &quot;,&quot;&lt;-10&gt;10&quot;}, {&quot;TZ_Etc_GMTp11 &quot;,&quot;&lt;-11&gt;11&quot;}, {&quot;TZ_Etc_GMTp12 &quot;,&quot;&lt;-12&gt;12&quot;}, {&quot;TZ_Etc_UCT &quot;,&quot;UTC0&quot;}, {&quot;TZ_Etc_UTC &quot;,&quot;UTC0&quot;}, {&quot;TZ_Etc_Greenwich &quot;,&quot;GMT0&quot;}, {&quot;TZ_Etc_Universal &quot;,&quot;UTC0&quot;}, {&quot;TZ_Etc_Zulu &quot;,&quot;UTC0&quot;}, {&quot;EOF&quot;, &quot;eof&quot;} }; char *getTimeZoneLit(int tzindex) { return(tz[tzindex].tzlit); } char *getTimeZone(int tzindex) { return(tz[tzindex].tzzone); } #endif // TZDB_H #endif </code></pre>
91550
|serial|string|buffer|char|
Problem cleaning string read from serial buffer
2022-12-06T12:31:56.570
<p>I am trying to move a <code>stepper motor</code> when a specific command is send to <code>Arduino Mega 2560</code>. This command is read character by character and stored in a <code>string variable</code>. Whenever a new command is sent, an act should be performed. However, it is not happening and I believe that the problem is in reading the sent command. I tried clearing the character and string variables, but to no avail. The sketch should run a loop that moves the motor <code>clockwise</code> or <code>counterclockwise</code> according to the command sent, which can be <code>&quot;crx*&quot;</code> for clockwise or <code>&quot;clx*&quot;</code> for anticlockwise, where <code>&quot;*&quot;</code> is the reading stop criterion of the characters. Any suggestions what to do? The script:</p> <pre><code>void(* resetFunc) (void) = 0;//Reset turn // Stepper Motor X const int stepPinX = 2; //X.STEP const int dirPinX = 5; // X.DIR const int pinEnable = 8; // String read char c; String readString; //main captured String // Unit steps double av_len = 1.029; //medium length double interval; int cnt_steps = 0; const int num_d = 200;//parameterized step int fact = int(num_d / av_len); int unit_len = fact * 1;//unit length (1mm) void setup() { // Sets pins as Outputs pinMode(stepPinX, OUTPUT); pinMode(dirPinX, OUTPUT); pinMode(pinEnable, OUTPUT); digitalWrite(pinEnable, HIGH);//lock driver on cnc shield Serial.begin(115200); Serial.setTimeout(1); while (1) { while ( (Serial.available() == 0) ) { } if (Serial.available()) { c = Serial.read(); //gets one byte from serial buffer //Serial.println(readString); if (c == '*') { Serial.println(readString);//test response if (readString == &quot;crx&quot;) { cnt_steps = cnt_steps + 1; Serial.println(cnt_steps); digitalWrite(pinEnable, LOW); digitalWrite(dirPinX, HIGH); for (int x = 0; x &lt; unit_len; x++) { digitalWrite(stepPinX, HIGH); delayMicroseconds(500); digitalWrite(stepPinX, LOW); delayMicroseconds(500); } } else if (readString == &quot;clx&quot;) { cnt_steps += -1; Serial.println(cnt_steps); digitalWrite(pinEnable, LOW); digitalWrite(dirPinX, LOW); for (int x = 0; x &lt; unit_len; x++) { digitalWrite(stepPinX, HIGH); delayMicroseconds(500); digitalWrite(stepPinX, LOW); delayMicroseconds(500); } } digitalWrite(pinEnable, HIGH);//lock driver on cnc shield c = (char)0; Serial.flush(); readString = &quot;&quot;; //resetFunc(); } else { readString += c; //makes the string readString } } } } void loop() { } </code></pre>
<p>In addition to the good responses you have already received, I offer this.</p> <p>For the Arduino, know the differences between String string and char arrays - there is much on this e.g., <a href="https://forum.arduino.cc/t/string-vs-string-vs-char-arrays-correct-approach/537468" rel="nofollow noreferrer">https://forum.arduino.cc/t/string-vs-string-vs-char-arrays-correct-approach/537468</a> . Many do not want to deal with the vagaries of String, but their use can be convenient.</p> <p>Run this code:</p> <pre><code>String readstring = &quot;xxx&quot;; void setup() { Serial.begin(115200); } void loop() { if (Serial.available()) { readstring = Serial.readStringUntil('/n'); Serial.print(readstring); Serial.println(&quot; received&quot;); if (readstring.equals(&quot;crx&quot;)) { // move counter clockwise Serial.println(&quot;moving counter clockwise&quot;); // counterclockwise() &lt;-- your function } else if (readstring.equals(&quot;clx&quot;) ) { // move clockwise Serial.println(&quot;moving clockwise&quot;); // clockwise() &lt;-- your function } else { // bad command Serial.println(&quot;Bad command received - no action&quot;); // badcommand() &lt;-- your function } } } </code></pre> <p>If you add functions for the stepper, it may do what you want within a limited context and with using the Arduino serial monitor for input. Take a look at the output.</p> <p><a href="https://i.stack.imgur.com/Ya3u0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ya3u0.jpg" alt="enter image description here" /></a></p> <p>Note that the serial monitor is set to &quot;no line ending&quot;. The terminating character '/n' is provide by your input in the serial monitor. It will do what you want, but again, many advise you stay away from String.</p>
91587
|arduino-ide|arduino-nano|motor|code-review|ultrasonics|
Single Method for 2 Ultrasonic Sensor is not working as expected
2022-12-10T18:52:41.527
<p>So I have created a method to read and return Ultrasonic Sensor Data. I have 2 Ultrasonic Sensors.</p> <p>Below is my code.</p> <pre> &nbsp;&nbsp;&nbsp;&#47;&#47; Ultrasonic Pins &nbsp;&nbsp;&nbsp;#define T1 2 &nbsp;&nbsp;&nbsp;#define E2 4 &nbsp;&nbsp;&nbsp;#define E1 3 &nbsp;&nbsp;&nbsp;#define T2 5 &nbsp;&nbsp;&nbsp;&#47;&#47; Motor Pins &nbsp;&nbsp;&nbsp;#define M1 7 &nbsp;&nbsp;&nbsp;#define M2 8 &nbsp;&nbsp;&nbsp;#define M3 9 &nbsp;&nbsp;&nbsp;#define M4 10 &nbsp;&nbsp;&nbsp;&#47;&#47; Motor Movements Definition &nbsp;&nbsp;&nbsp;enum MOTOR &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;FORWARD, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BACKWARD, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LEFT, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RIGHT, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;STOP &nbsp;&nbsp;&nbsp;}; &nbsp;&nbsp;&nbsp;long duration1, distance1, duration2, distance2; &nbsp;&nbsp;&nbsp;void setup() &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.begin(9600); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(E1, INPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(E2, INPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(T1, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(T2, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(M1, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(M2, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(M3, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pinMode(M4, OUTPUT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(STOP); &nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;void loop() &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#47;&#47; If Both Sensors detect object then go in backward Direction &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (DetectObject(T1,E1,1) &lt; 10 &amp;&amp; DetectObject(T2,E2,2) &lt; 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.println(&#34;Backward&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(BACKWARD); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(200); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(STOP); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(50); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#47;&#47; If Left Sensor detect object then go in Right Direction &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (DetectObject(T1,E1,1) &lt; 10 &amp;&amp; DetectObject(T2,E2,2) &gt; 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.println(&#34;Right&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(RIGHT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(200); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(STOP); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(50); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#47;&#47; If Right Sensor detect object then go in Left Direction &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (DetectObject(T1,E1,1) &gt; 10 &amp;&amp; DetectObject(T2,E2,2) &lt; 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.println(&#34;Left&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(LEFT); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(200); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(STOP); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(50); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#47;&#47; If Both Sensors detect no object then go in Forward Direction &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (DetectObject(T1,E1,1) &gt; 10 &amp;&amp; DetectObject(T2,E2,2) &gt; 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.println(&#34;Forward&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(FORWARD); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(200); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Motor(STOP); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(50); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;void Motor(MOTOR motor) &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;switch (motor) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case STOP: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M1, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M2, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M3, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M4, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case FORWARD: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M1, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M2, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M3, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M4, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case BACKWARD: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M1, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M2, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M3, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M4, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case LEFT: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M1, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M2, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M3, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M4, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case RIGHT: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M1, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M2, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M3, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(M4, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delay(100); &nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;long DetectObject(uint8_t trigPin, uint8_t echoPin, int sensorNo) &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(trigPin, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delayMicroseconds(2); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(trigPin, HIGH); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delayMicroseconds(10); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;digitalWrite(trigPin, LOW); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.print(&#34;Distance Sensor&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.print(sensorNo); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.print(&#34;: &#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.print(pulseIn(echoPin, HIGH) * 0.034 &#47; 2); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serial.println(&#34; cm&#34;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return pulseIn(echoPin, HIGH) * 0.034 &#47; 2; &nbsp;&nbsp;&nbsp;} </pre> <p>I am getting continuously getting <code>Backward</code> in the Serial monitor.</p> <p>Output of Serial Monitor -</p> <pre><code>Distance Sensor1: 20 cm Distance Sensor2: 15 cm Backward Distance Sensor1: 17 cm Distance Sensor2: 21 cm Backward Distance Sensor1: 24 cm Distance Sensor2: 9 cm Backward </code></pre> <p>But when I created 2 different methods for each Ultrasonic Sensor. It is working fine.</p> <p>I want to have a single method for N number of Ultrasonic Sensors.</p> <p>Thanks in Advance!</p>
<p>The problem lies in the function, that does the ultrasonic detection. First I would suggest to not do Serial printing between the trigger pulse and <code>pulseIn()</code>, since the Serial transmission might take longer (for example when the buffer is full) and then your reading is garbage. Execute <code>pulseIn()</code> directly after the trigger pulse part and save the result in a local variable, which you can later print and return. If you do that, your problem is also solved.</p> <p>For understanding what actually happens with your code, I annotated the function with some comments:</p> <pre><code>long DetectObject(uint8_t trigPin, uint8_t echoPin, int sensorNo) { // Create Trigger pulse digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Do some printing Serial.print(&quot;Distance Sensor&quot;); Serial.print(sensorNo); Serial.print(&quot;: &quot;); // Read a pulse and print it directly to Serial Serial.print(pulseIn(echoPin, HIGH) * 0.034 / 2); Serial.println(&quot; cm&quot;); // Read ANOTHER pulse and return it return pulseIn(echoPin, HIGH) * 0.034 / 2; } </code></pre> <p>As you can see, you are trying to read 2 pulses. But there is only one echo pulse. That one pulse is read by the first execution of <code>pulseIn()</code> and you print the result to Serial, so in the Serial Monitor you are seeing the correct value.</p> <p>After that you are executing <code>pulseIn()</code> again and returning the result. <code>pulseIn()</code> will wait for a pulse to begin (so it can start counting the time). But there is no second pulse on the echo line, so <code>pulseIn()</code> will exit after a timeout (by default 1s). On timeout this function returns zero. So every time you execute this function, it will return zero.</p> <p>If you then look at the logic in <code>loop()</code>, you can easily see why you are only getting backwards. The code is stuck in the first while loop, because the value returned from the function is always zero, which is smaller than 10.</p> <p>Here is a pseudo code version of how your function really should work:</p> <pre><code>execute trigger pulse execute pulseIn function and save result in local variable print whatever you want to Serial return the value of the local variable </code></pre>
91601
|lcd|library|spi|u8glib|
I need help with creating a menu using u8g2 library
2022-12-11T19:17:10.200
<p>I want to make a project with a (Nokia 5110) display using u8g2 library. Here I have the code for my program:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Arduino.h&gt; #include &lt;U8g2lib.h&gt; #include &lt;TM1637Display.h&gt; #include &lt;EEPROM.h&gt; #ifdef U8X8_HAVE_HW_SPI #include &lt;SPI.h&gt; #endif #ifdef U8X8_HAVE_HW_I2C #include &lt;Wire.h&gt; #endif #define LED_PIN 5 #define BUTTON_PIN 6 #define BUZZ_PIN 7 #define BUTTON_L 2 #define BUTTON_R 3 #define BUTTON_START 4 //48x84 disp. U8G2_PCD8544_84X48_F_4W_SW_SPI u8g2(U8G2_R2, 13, 11, 10, 12, 8); //rotate, clk, DIN, CE, DC, RST // byte lastButtonState = 0; byte ledState; float cpu_gauge = 0.0; char buffer[40]; int move = 7; float cpu_gauge_step = 0.5; byte eeprom_led; void set_led(){ if( digitalRead(LED_PIN) == 1 ) ledState = 1; if( digitalRead(LED_PIN) == 0 ) ledState = 0;} void backlight(){ byte buttonState = digitalRead(BUTTON_PIN); //monitor button state if (buttonState != lastButtonState) { //check if not equal lastButtonState = buttonState; //if prev. true, make equal if (buttonState == HIGH) { ledState = (ledState == HIGH) ? LOW : HIGH; digitalWrite(LED_PIN, ledState); }}} void status_bar(){ if (cpu_gauge &gt; cpu_gauge_step*1) u8g2.drawBox(2,13,6,8); //x, y , size in x, size in y if (cpu_gauge &gt; cpu_gauge_step*2) u8g2.drawBox(2 + 1*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*3) u8g2.drawBox(2 + 2*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*4) u8g2.drawBox(2 + 3*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*5) u8g2.drawBox(2 + 4*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*6) u8g2.drawBox(2 + 5*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*7) u8g2.drawBox(2 + 6*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*8) u8g2.drawBox(2 + 7*move,13,6,8); if (cpu_gauge &gt; cpu_gauge_step*9) u8g2.drawBox(2 + 8*move,13,6,8); if (cpu_gauge &gt;= cpu_gauge_step*10) u8g2.drawBox(2 + 9*move,13,6,8); } void setup(void) { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); pinMode(BUZZ_PIN, OUTPUT); pinMode(BUTTON_L, INPUT); pinMode(BUTTON_R, INPUT); pinMode(A7, INPUT); pinMode(BUTTON_START, INPUT); eeprom_led = EEPROM.read(0); digitalWrite(LED_PIN, eeprom_led); set_led(); //sets the led state to 1 or 0 depending on digital write Serial.begin(9600); u8g2.begin(); } void loop(void) { EEPROM.update(0,ledState); /*pomiar = EEPROM[ 0 ]; delay(2500);// Serial.println(pomiar);// Serial.println(cpu_gauge); int pomiar = digitalRead(BUTTON_START); Serial.println(pomiar);*/ backlight(); cpu_gauge = analogRead(A7) * (5.0/1022); u8g2.firstPage(); do { u8g2.drawRFrame(0,12,74,10,3); //pos X,Y length, width, corner status_bar(); u8g2.setFont(u8g2_font_busdisplay8x5_tr); u8g2.setCursor(0,8); char pomiar_str[5]; dtostrf(cpu_gauge,0,2, pomiar_str); sprintf(buffer, &quot;LOAD: %sV&quot;, pomiar_str); u8g2.print(buffer); u8g2.setCursor(0,36); u8g2.print(&quot;bckgrnd_tsks:&quot;); u8g2.setCursor(48,48); sprintf(buffer, &quot;led: %d&quot;, ledState); u8g2.print(buffer); u8g2.drawStr(0,48,&quot;buzz:&quot;); if (cpu_gauge &gt; 4.80){ digitalWrite(7,1); u8g2.setCursor(0,48); u8g2.setFont(u8g2_font_busdisplay8x5_tr); u8g2.setFont(u8g2_font_open_iconic_play_1x_t); u8g2.drawGlyph(27, 48, 0x0040);} else digitalWrite(7,0); } while ( u8g2.nextPage() );} </code></pre> <p>I have succesfully made a program, that:</p> <p>-Has a pushbutton, to turn off, and on the backlight with each press<br /> -Writes to the EEPROM the state of the LED, and reads it at startup<br /> -Displays an analogRead value, from the potentiometer and also displays a progress bar of the given value<br /> -Displays the state of the backlight<br /> -Turns on the buzzer, if the analogRead value exceedes some value<br /> -Displays an indicator, if the buzzer is turned on</p> <p>Now, let's assume that what this program does, is called option &quot;A&quot;, and A in this example works all the time, because there is nothing else. I want to create a menu, that would have option A, B, C, D. Assume that formatting and pushbutton actions, doesn't matter for now.</p> <p>A: Is what was described before.<br /> B: Clock. Just display a clock.<br /> C: Stopwatch.<br /> D: Setting the time.</p> <p>I see two ways of creating such menu.</p> <p>1: Is to build a selectable/scrollable menu that would have labels, and by choosing, and pressing a button, we would enter desired function.<br /> 2: Ditch the selectable menu. One pushbutton will switch from option A to D. Something like a casio watch.</p> <p>I'd prefer the second option, I think it'll be easier to do</p> <p>What I don't understand, is the U8G2 reference manual. I don't really understand the concept of the buffer, sendBuffer, userInterfaceSelectionList, and some more stuff, that I can't name for now.</p> <p>My understanding is, that i have to make some array, of functions. Like:</p> <pre><code>Array [] = {default_display();, clock();, stopwatch();, setting();) </code></pre> <p>And with a button, I'd go thru this array like so:</p> <pre><code>Array = 0; If (digitalRead(some_button_pin) == High){ Array + 1;} If (Array &gt; 3){ Array = 0;} </code></pre> <p>And in those funtions, it would have implemented options, like the backlight turned on, or something else, whatever,</p> <p>Now I don't know if that makes any sense. If it's transferable into code. I don't know if I need to clear the display, and how do I do that only once before entering the option. How do I make it, so that all the variables related to clock, the stopwatch still work even if I'm not displaying it. I'm honestly lost, and I just need guidance with this, becuase I have only had C for 1 semester at Electrical Engineering. I'm not a programist, but I really want to make it work, but it just isn't explained in the way like I don't know, pulldown resistors, where you can make some assumptions, and with them explain how something works. No, it looks like this:</p> <pre><code>void u8g2_SetBufferPtr(u8g2_t *u8g2, uint8_t *buf) </code></pre> <p>And yeah, I just don't know how do I go around it, how do I navigate in it. Thank you for any help.</p>
<p>I have figured it out. First thing that has to be said. If you're used to creating function definitions before the setup, you can't do that with u8g2 library. You can create function definitions after calling u8g2.begin in setup. Now there are two ways how you can do it, in the &quot;Casio watch&quot; fashion, but first create a varaible that will read how many times you've clicked, and store that somewhere, and add a condition, that will revert it to 1 after some amount of clicks. 1st way: Create a switch case, where the variable will be your switch, and in the cases (x to n) write what you want, graphics, text, whatever. Now the problem that I've had, is that when I've pasted the same code, and changed only some minor text, the whole thing glitched. It went through 1 and 2, normally, and then everything from case 3 and 4 was merged toghether, and case 4 was empty, and so was the screen. I couldn't fix it, so I came up with the second approach. Create as many IF conditions, as you have menu option. So it goes like this: If (menu_counter == 1){ //your input to the screen// } And so for the rest. As far as I have tested this, it works, even if the code is the same for both IF statements. Now I'd have to implement the menu selection list on top. Leaving the answer to my own question, hopefully someone will find it useful.</p>
91608
|esp8266|
Changing ESP8266 WiFi network via Access Point
2022-12-12T05:48:54.063
<p>I have an ESP8266 project that requires setting the SSID and password for a network via an Access Point. Everything works fine, the only issue is if you send incorrect credentials to the access point, the server returns an empty response before the timeout period elapses, and the error message is never sent to the client.</p> <p>If the connection is successful then the success message is appropriately sent to the client. It's almost like the <code>WiFi.begin()</code> function detects the connection fails on its own, and something there is preventing me from sending my own response.</p> <pre><code>% curl -X POST &quot;http://192.168.1.1/authenticate?ssid=FakeNetworkpassword=87654321&quot; curl: (52) Empty reply from server </code></pre> <p>Did some research and saw some mentions to keep the <code>loop</code> running, so I attempted to do so below, but to no avail. Would appreciate any ideas, thanks.</p> <pre><code>#include &quot;ESP8266WiFi.h&quot; #include &quot;ESP8266HTTPClient.h&quot; #include &quot;ESP8266WebServer.h&quot; HTTPClient http; WiFiClient client; ESP8266WebServer server(80); IPAddress ipAP(192, 168, 1, 1); IPAddress gateway(192, 168, 1, 1); IPAddress subnet(255, 255, 255, 0); unsigned long previousMillisConnection = 0; unsigned long startingMillisConnection = 0; const unsigned long CONNECTION_PERIOD = 1000; const unsigned long CONNECTION_TIMEOUT = 10000; int DELAY = 40; char ssid[64] = { 0 }; char password[64] = { 0 }; char ssidNew[64]; char passNew[64]; const int STATE_DEFAULT = 0; const int STATE_CREDS = 1; int state = STATE_DEFAULT; void setup() { Serial.begin(9600); WiFi.softAPConfig(ipAP, gateway, subnet); WiFi.softAP(&quot;ESP8266&quot;, &quot;12345678&quot;); delay(100); server.on(&quot;/authenticate&quot;, HTTP_POST, onSetCredentials); server.begin(); performWifiConnect(ssid, password); WiFi.waitForConnectResult(CONNECTION_TIMEOUT); Serial.println(&quot;Initialization complete&quot;); } void loop() { if (state == STATE_DEFAULT) { server.handleClient(); if (WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Connected!&quot;); } } else if (state == STATE_CREDS) { whileConnecting(); } delay(DELAY); } void performWifiConnect(char ssid[], char password[]) { Serial.println(&quot;Attempting to connect to &quot; + String(ssid) + &quot;...&quot;); WiFi.setAutoReconnect(false); WiFi.persistent(false); WiFi.begin(ssid, password); } void onWifiConnected() { Serial.println(&quot;WiFi connected &quot; + WiFi.localIP().toString()); WiFi.setAutoReconnect(true); WiFi.persistent(true); } void onSetCredentials() { Serial.println(&quot;onSetCredentials&quot;); server.arg(&quot;ssid&quot;).toCharArray(ssidNew, 64); server.arg(&quot;password&quot;).toCharArray(passNew, 64); if (String(ssidNew) == String(ssid) &amp;&amp; WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Already connected to &quot; + String(ssidNew)); server.send(200, &quot;application/json&quot;, &quot;{ \&quot;success\&quot;: true, \&quot;changed\&quot;: false }&quot;); } else { Serial.println(&quot;Switching from &quot; + String(ssid) + &quot; to &quot; + String(ssidNew)); state = STATE_CREDS; performWifiConnect(ssidNew, passNew); startingMillisConnection = millis(); } } void whileConnecting() { unsigned long currentMillis = millis(); if (currentMillis - previousMillisConnection &gt;= CONNECTION_PERIOD) { previousMillisConnection = currentMillis; Serial.println(&quot;checking connection...&quot;); // Success if (WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Connected to &quot; + String(ssidNew) + &quot; successfully!&quot;); strcpy(ssid, ssidNew); strcpy(password, passNew); server.send(200, &quot;application/json&quot;, &quot;{ \&quot;success\&quot;: true, \&quot;changed\&quot;: true }&quot;); state = STATE_DEFAULT; } // Failure if (currentMillis - startingMillisConnection &gt;= CONNECTION_TIMEOUT) { Serial.println(&quot;connection failed, attempting to reconnect to old network!&quot;); Serial.println(&quot;ssidOld: &quot; + String(ssid)); Serial.println(&quot;passOld: &quot; + String(password)); String errorMessage = &quot;Timed out while attempting to connect to &quot; + String(ssidNew); Serial.println(errorMessage); server.send(500, &quot;application/json&quot;, &quot;{\&quot;errorMessage\&quot;:\&quot;&quot; + errorMessage + &quot;\&quot;}&quot;); performWifiConnect(ssid, password); WiFi.waitForConnectResult(CONNECTION_TIMEOUT); state = STATE_DEFAULT; if (WiFi.status() != WL_CONNECTED) { Serial.println(&quot;Could not return to old network!&quot;); } } } } </code></pre>
<p>There are several intertwined issues in this one.</p> <p>Firstly, <code>setup()</code> has some code running before it should be.</p> <p>That first problem is here:</p> <pre><code> server.on(&quot;/authenticate&quot;, HTTP_POST, onSetCredentials); server.begin(); performWifiConnect(ssid, password); WiFi.waitForConnectResult(CONNECTION_TIMEOUT); </code></pre> <p>You've already set <code>ssid</code> and <code>password</code> to be null, and server.begin() won't run the server yet (I'll get to that issue in a minute), so this is setting your credentials to be null at the start of the program. There's no point in running <code>waitForConnectResult()</code> then, because there is nothing to connect. There may be logic in setting <code>performWifiConnect()</code> though, since if you've ever set the Wi-Fi credentials with <code>wifi.begin()</code> <em>before</em> turning off persistent, those credentials are still remembered (it just won't remember new ones).</p> <p>The next issue is that you're only handling server requests while the connection <em>is not invalid</em>. Thus, when there is an invalid credential for the network, the server doesn't run, and you don't get a response.</p> <pre><code>void loop() { if (state == STATE_DEFAULT) { server.handleClient(); if (WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Connected!&quot;); } } else if (state == STATE_CREDS) { whileConnecting(); } delay(DELAY); } </code></pre> <p>As you can see, <code>server.handleclient()</code> (the actual server; the ability to respond to requests) is only running while it does not have <code>state == STATE_DEFAULT</code>. <em>That</em> is then changed, <code>state = STATE_CREDS;</code>, during the callback for getting network credentials. You'll probably get a reply from the request handler that's currently running, but this will otherwise cause you problems since the server then never responds to any future requests. You <strong>must</strong> continually call <code>server.handleclient()</code> or nothing server-related will work.</p> <p>But, something else is also wrong. You can only pass replies back from the server if you actually send them <em>while the server is still processing a request.</em></p> <pre><code>else { Serial.println(&quot;Switching from &quot; + String(ssid) + &quot; to &quot; + String(ssidNew)); state = STATE_CREDS; performWifiConnect(ssidNew, passNew); startingMillisConnection = millis(); } </code></pre> <p>As you can see, there is no <code>server.send()</code> in this branch, so you'll get no reply. This is likely the most immediate cause of your problem with an empty response.</p> <p>Instead, you have that in the function <code>whileConnecting()</code>. As noted earlier, the server cannot send replies that aren't in the function it calls when it gets a request, or in functions called by that function. The server does not call <code>whileConnecting()</code>, <code>loop()</code> does. So it can't see or send that reply.</p> <p>(Side note: This requirement of the server is implemented pretty weirdly, since you're calling server methods while one of its methods calls your code, only for the server to then ask itself what you told it while it was busy with your request, grab that buffer, and return it to the client. But it <strong>only</strong> does that check somewhere inside <code>server.handleClient()</code>, and other <code>send()</code> calls will either be ignored or get queued to send the next time the client makes a request.)</p> <p>If you were to wait for a connection inside the server's request handler instead, and then send the error/success messages there too, this might work. It's still bad practice since the server (that part I said you always want to <strong>not</strong> hold up) and the entire rest of your code will be on hold while it waits to connect, but you'll <em>probably</em> have it work <strong>as long as there's nothing else time-critical or important going on</strong>.</p> <p>The best approach would be to have your client poll a second address (or just the same address with no POST values, then have the server check whether there are no args) and have that say whether it is currently connected.</p> <p>On that note, your connection checking code also has a problem. <code>loop()</code> has a delay in it, which is already going to bog things down. But you also have the whileConnecting function check for elapsed time. This <em>is</em> the proper way to coordinate multiple independent check-back-and-do-stuff operations, so you're aware of it, but this hasn't been transferred to the rest of the code.</p> <p>Except, <strong>also</strong> in whileConnecting, you then call <code>WiFi.waitForConnectResult(CONNECTION_TIMEOUT);</code>. This will <strong>block</strong> that function until a result is present, which thus halts everything else for however long that timeout is. The only place you &quot;should&quot; use this (again, probably bad practice) is inside the server if you were trying to have it directly reply with the connection status <strong>or</strong> if there's not anything else important going on (which there is, so this is an issue). Since you're already running code periodically on a timer, just have this code check for the timeout directly (easiest method: call the connect function with the credentials, set the check-back time by <code>timeout</code>, then check again), and just reconnect then instead of forcing a wait. This will leave the server and the rest of your code responsive.</p> <p>Now, with all (well, most) of that put together: (NOTE: This code will need some changes made to the rest of your code, and may require adjustment itself, but it should get you very close. I suggest making a backup copy of your code first in case you need to reference or fix something. I also wrote this in a text editor, as I don't currently have access to the IDE to test this. There might be minor errors.)</p> <p>Solution A (have the server wait and tell you the results): (NOTE: also, delete <code>whileConnecting()</code> and all the <code>state</code> if you use this method; you want to make sure server.handleClient() is always being called until the connection is actually successful, or just plain always.)</p> <pre><code>void onSetCredentials() { Serial.println(&quot;onSetCredentials&quot;); server.arg(&quot;ssid&quot;).toCharArray(ssidNew, 64); server.arg(&quot;password&quot;).toCharArray(passNew, 64); if (String(ssidNew) == String(ssid) &amp;&amp; WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Already connected to &quot; + String(ssidNew)); server.send(200, &quot;application/json&quot;, &quot;{ \&quot;success\&quot;: true, \&quot;changed\&quot;: false }&quot;); } else { Serial.println(&quot;Switching from &quot; + String(ssid) + &quot; to &quot; + String(ssidNew)); performWifiConnect(ssidNew, passNew); startingMillisConnection = millis(); //code to detect the server connection status and respond starts here// WiFi.waitForConnectResult(CONNECTION_TIMEOUT); if (WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Connected to &quot; + String(ssidNew) + &quot; successfully!&quot;); strcpy(ssid, ssidNew); strcpy(password, passNew); server.send(200, &quot;application/json&quot;, &quot;{ \&quot;success\&quot;: true, \&quot;changed\&quot;: true }&quot;); } // Failure if (currentMillis - startingMillisConnection &gt;= CONNECTION_TIMEOUT) { Serial.println(&quot;connection failed, attempting to reconnect to old network!&quot;); Serial.println(&quot;ssidOld: &quot; + String(ssid)); Serial.println(&quot;passOld: &quot; + String(password)); String errorMessage = &quot;Timed out while attempting to connect to &quot; + String(ssidNew); Serial.println(errorMessage); server.send(500, &quot;application/json&quot;, &quot;{\&quot;errorMessage\&quot;:\&quot;&quot; + errorMessage + &quot;\&quot;}&quot;); } } } </code></pre> <p>This solution (A) will <em>probably</em> give you the connection status back, assuming the Wi-Fi connection attempt times out before the cURL request/server does. I haven't actually tested this and I did mention it's kinda bad practice.</p> <p>Solution B (Poll the server for connection status rather than waiting for a reply): (Note: Again, delete any <code>state</code> logic and <code>whileConnecting()</code> from the other code.)</p> <pre><code>void onSetCredentials() { Serial.println(&quot;onSetCredentials&quot;); if (!server.hasArg(&quot;ssid&quot;)){ //check for no-arg request and return conn status// server.send(&quot;200&quot;, &quot;text/plain&quot;, (WiFi.status() != WL_CONNECTED)? &quot;Connected&quot; : &quot;Not Connected&quot;); //or whatever other message(s) you want //You may also want to add some sort of Serial.print()-type logging here too, since I didn't.// } else{ //existing connection setup request handler resumes here// server.arg(&quot;ssid&quot;).toCharArray(ssidNew, 64); server.arg(&quot;password&quot;).toCharArray(passNew, 64); if (String(ssidNew) == String(ssid) &amp;&amp; WiFi.status() == WL_CONNECTED) { Serial.println(&quot;Already connected to &quot; + String(ssidNew)); } else { Serial.println(&quot;Switching from &quot; + String(ssid) + &quot; to &quot; + String(ssidNew)); performWifiConnect(ssidNew, passNew); startingMillisConnection = millis(); } } } </code></pre> <p>With Solution B, you can call the cURL command to the ESP8266 <em>without</em> the <code>ssid</code> and <code>password</code> set, and you'll get a connection status back instead. This may take a few attempts while it's still in the process of connecting, but if it <em>remains</em> not connected, you know the credentials are wrong.</p>
91612
|arduino-ide|esp32|
Why am I receiving this Error: Debug exception reason: Stack canary watchpoint triggered (task1) in ESP32 using a FreeRTOS program?
2022-12-12T10:21:56.260
<p>I'm getting this error by running a FreeRTOS program on my ESP32 using arduino ide, I don't understand why this happens because this same program works on an arduino Uno with no errors:</p> <pre><code>Guru Meditation Error: Core 0 panic'ed (Unhandled debug exception). Debug exception reason: Stack canary watchpoint triggered (task1) Core 0 register dump: PC : 0x40088a4f PS : 0x00060636 A0 : 0x800d3155 A1 : 0x3ffb9130 A2 : 0x3ffb8eb4 A3 : 0xffffffff A4 : 0x00060620 A5 : 0x00060623 A6 : 0x00060623 A7 : 0x00000001 A8 : 0x00000001 A9 : 0x00000000 A10 : 0x00060623 A11 : 0x00000000 A12 : 0x00000000 A13 : 0x00000000 A14 : 0x007bee88 A15 : 0x003fffff SAR : 0x00000000 EXCCAUSE: 0x00000001 EXCVADDR: 0x00000000 LBEG : 0x00000000 LEND : 0x00000000 LCOUNT : 0x00000000 </code></pre> <p>This is the code I'm using:</p> <pre><code>//#include &lt;Arduino_FreeRTOS.h&gt; //Overload happens if xTaskGetTickCount – lastTickCount (the first parm to vTaskDelayUntil) is &gt;= period in ticks void task1(void *pvParameters); void task2(void *pvParameters); void task3(void *pvParameters); void setup() { Serial.begin(115200); //Create tasks //xTaskCreate(Task function, Task name, , Task parameter, Task priority, ); Serial.println(&quot;111111&quot;); xTaskCreate(task1, &quot;task1&quot;, 512, NULL, 1, NULL); Serial.println(&quot;222222&quot;); xTaskCreate(task2, &quot;task2&quot;, 512, NULL, 2, NULL); xTaskCreate(task3, &quot;task3&quot;, 512, NULL, 3, NULL); //vTaskStartScheduler(); } void loop() {} void task1(void *pvParameters) { (void) pvParameters; TickType_t waketime, period = 1000 / portTICK_PERIOD_MS; waketime = xTaskGetTickCount(); while(1){ Serial.println('M'); //This happens almost immediately, so we need to add an artificial delay, a to simulate a task running for a few ms, it only serves as a notification that the task started vTaskDelay(10); if(xTaskGetTickCount() - waketime &gt;= period) Serial.println(&quot;Overload in task 1&quot;); vTaskDelayUntil(&amp;waketime, period); } } void task2(void *pvParameters) { (void) pvParameters; TickType_t waketime, period = 1000 / portTICK_PERIOD_MS; waketime = xTaskGetTickCount(); while(1) { Serial.println('E'); //This happens almost immediately, so we need to add an artificial delay, a to simulate a task running for a few ms, it only serves as a notification that the task started vTaskDelay(10); if(xTaskGetTickCount() - waketime &gt;= period) Serial.println(&quot;Overload in task 2&quot;); vTaskDelayUntil(&amp;waketime, period); } } void task3(void *pvParameters) { (void) pvParameters; TickType_t waketime, period = 1000 / portTICK_PERIOD_MS; waketime = xTaskGetTickCount(); while(1) { Serial.println('S'); //This happens almost immediately, so we need to add an artificial delay, a to simulate a task running for a few ms, it only serves as a notification that the task started vTaskDelay(10); if(xTaskGetTickCount() - waketime &gt;= period) Serial.println(&quot;Overload in task 3&quot;); vTaskDelayUntil(&amp;waketime, period); } } </code></pre> <p>I tried increasing the task stack memory in xtaskcreate and the same error occurs, although when I increased it to 1024 nothing shows up in the serial monitor. This same program works flawlessly on arduino uno and raspberry pi pico. I also tried changing the tasks' period and their execution time, which is the delay, and it still doesn't work</p>
<blockquote> <p>although when I increased it to 1024 nothing shows up in the serial monitor.</p> </blockquote> <p>Doing nothing to your code except using 4096 for stack size causes it to print things on serial.</p> <pre><code>rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0030,len:1344 load:0x40078000,len:13864 load:0x40080400,len:3608 entry 0x400805f0 111111 222222M E S S E M S ME </code></pre> <p>I won't tell you that it's correct, but it seems fairly clear that you haven't given it enough stack to work with.</p> <p>With my current setup</p> <pre class="lang-cpp prettyprint-override"><code>Serial.println(configMINIMAL_STACK_SIZE); </code></pre> <p>is printing 828. I don't know how exactly how to interpret that number. But unless I found otherwise, I could default to considering it the requirement to start a task that uses no stack of it own (no local variables, no calling). The memories of the esp32 seem large enough that no matter how you're using them it doesn't make sense to go so minimal for a handful to tasks. I chose 4096 somewhat arbitrarily. I'm not suggesting is a good value.</p>
91619
|pwm|frequency|
Arduino 75kHz output frequency setup
2022-12-12T22:49:08.340
<p>i don't know how to manipulate arduino uno or mega registers and timers to be close to 75kHz output frequency. Could you help please ?</p>
<p>I think the answer given by Edgar Bonet is the right one, all things considered, and I up-voted it for that reason.</p> <p>For S&amp;G, I want to add the following:</p> <ol> <li>The <strong>easiest</strong> way is to simply use the tone(GPIO,Frequency); command - and there are caveats. <strong>BUT</strong>, the frequency argument is an unsigned int so the fastest frequency is 65535Hz - it will do you no good for 75kHz.</li> </ol> <p>Using a frequency counter and an UNO (crystal), tone(10,65535); the output was 65556/8 Hz. On a Pro Mini 5V (ceramic resonator as I recall), it was 65540 Hz.</p> <ol start="2"> <li>Again, for S&amp;G, I tried this code (and adjusted the number of NOPs) to get as close as I could to 75kHz:</li> </ol> <p>void setup() { pinMode(10, OUTPUT); }</p> <pre><code>void loop() { here: digitalWrite(10, HIGH); delayMicroseconds(3); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); digitalWrite(10, LOW); delayMicroseconds(3); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); __asm__(&quot;nop\n\t&quot;); goto here; } </code></pre> <p>The output on the UNO was 75004/6 Hz - not too bad. On the Pro Mini, the best I could do was 74986 Hz.</p> <p>Of course, we are talking about square waves.</p>
91620
|arduino-uno|programming|wires|keypad|
4x3 keypad not providing any output and the output it does provide is incorrect
2022-12-12T23:16:04.820
<p>I am trying to figure out how to use a 4x3 keypad and just want to receive the key numbers I select on the serial monitor. The problem I am getting is that some of the keys I type don't give me any output and then the keys that do provide output do not match their corresponding number. For example key 1 does not provide any output, whereas keys 3 and 4 give an output of 4 and 9 respectively. I have attached pictures of how the keypad is connected <a href="https://i.stack.imgur.com/y70Yl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y70Yl.jpg" alt="Wiring that I used to connect the pins" /></a> <a href="https://i.stack.imgur.com/6OTz0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6OTz0.jpg" alt="Close up of the pins" /></a> <a href="https://i.stack.imgur.com/awCP5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awCP5.jpg" alt="wire diagram" /></a></p> <p>The code that I am using is below:</p> <pre><code>#include &lt;Keypad.h&gt; // Constants for row and column sizes const byte ROWS = 4; const byte COLS = 3; // Array to represent keys on keypad char hexaKeys[ROWS][COLS] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; // Connections to Arduino byte rowPins[ROWS] = {9, 8, 7, 6}; byte colPins[COLS] = {5, 4, 3}; // Create keypad object Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); void setup() { // Setup serial monitor Serial.begin(9600); } void loop() { // Get key value if pressed char customKey = customKeypad.getKey(); if (customKey) { // Print key value to serial monitor Serial.println(customKey);} } </code></pre> <p>I just need help identifying where I am going wrong and how I can fix the problem I am having. Thanks.</p>
<p>I determined where I was going wrong. The keypad has a different wiring compared to the traditional way of doing it. I found this <a href="https://electropeak.com/learn/interfacing-4x3-membrane-matrix-keypad-with-arduino/" rel="nofollow noreferrer">this</a> article helpful. The changes made to the code are as follows:</p> <pre><code>byte rowPins[ROWS] = {8, 3, 4, 6}; byte colPins[COLS] = {7, 9, 5}; </code></pre> <p>As can be seen, the rows and columns pins need to be changed.</p> <p><a href="https://i.stack.imgur.com/GoWUr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GoWUr.jpg" alt="Diagram showing what connections are for rows and which ones are for columns" /></a></p>
91621
|led|interrupt|button|debounce|
Interrupt on button press + debouncing
2022-12-13T00:32:32.257
<p>I want to have an interrupt function executed whenever a button is pressed. The button is connected to <code>pin 2</code> and the <code>GND</code>. Therefore, the pin is turned to <code>LOW</code> whenever the button is pressed. In addition to that, proper debouncing should be used As a proof of concept, the interrupt function should just toggle the <code>BUILTIN_LED</code> whenever the button is pressed.</p> <p>I have tried many different approaches but i cannot make it work.</p> <p>This is my last iteration:</p> <pre><code>bool led_status = LOW; // current state of output pin int buttonState; // the current reading from the input pin int lastButtonState = HIGH; //the previous reading from the input pin // the following variables are unsigned longs because the time, measured in // milliseconds, will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime = 0; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers int button_switch = 2; // external interrupt pin bool initialisation_complete = false; // inhibit any interrupts until initialisation is complete // ISR for handling interrupt triggers arising from associated button switch // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: void button_interrupt_handler() { //static long int elapse_timer; if (initialisation_complete == true) //only able to run the ISR when arduino has finished initialization { // new interrupt so okay start a new button read process - // now need to wait for button release plus debounce period to elapse // this will be done in the button_read function int reading = digitalRead(button_switch); if ( reading != lastButtonState) // If the switch changed, due to noise or pressing: { lastDebounceTime = millis(); // reset the debouncing timer } // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: if ( (millis() - lastDebounceTime) &gt; debounceDelay) { if (reading != buttonState) // if the button state has changed: { buttonState = reading; if (buttonState == HIGH) // only toggle the LED if the new button state is HIGH { led_status = !led_status; } } } digitalWrite(LED_BUILTIN, led_status); //set the LED lastButtonState = reading; // save the reading. Next time through the loop, it'll be the lastButtonState: } } // end of button_interrupt_handler void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(button_switch, INPUT_PULLUP); //no res = change to INPUT_PULLUP attachInterrupt(digitalPinToInterrupt(button_switch), button_interrupt_handler, FALLING); //no res = change to FALLING digitalWrite(LED_BUILTIN, led_status); initialisation_complete = true; // open interrupt processing for business } void loop() { //do nothing } </code></pre> <p>I am not sure what I am doing wrong or why this does not work.</p> <p>EDIT: When I press the button, nothing happens at all.</p>
<p>Take a look at this line in your code - the very first thing that is done in the ISR,</p> <p><em>int reading = digitalRead(button_switch);</em></p> <p>I think that the reason that your program does not “do anything” is because you are reading the button state inside the ISR and, because you trigger an interrupt on a falling edge, you will ALWAYS see 0 as the button state at that point. It can never change when you read it once at the beginning of the ISR, it will always =0, unless you stay in the ISR and wait for a change, which is a very, very, bad idea.</p> <p>The rest of your comparisons and detections all fail because within the ISR, the button read is always going to be the same and = 0, because that is how you got to the ISR. As far as your program is concerned, the button has never been pressed or depressed.</p> <p>It is true, depending on how you configure the button; a single state change will be detected because of initialization, but that is besides the point.</p> <p>You can test this yourself by moving all of your variables to volatile globals and then in your loop run this:</p> <pre><code>void loop() { Serial.print(&quot;lastButtonState &quot;); Serial.println(lastButtonState); Serial.print(&quot;buttonState &quot;); Serial.println(buttonState); Serial.print(&quot;reading &quot;); Serial.println(reading); } </code></pre> <p>You may have other problems, but that one stuck out to me.</p> <p>I would suggest that you take a look at this project and see how he is doing it - <a href="https://create.arduino.cc/projecthub/ronbentley1/button-switch-using-an-external-interrupt-7879df" rel="nofollow noreferrer">https://create.arduino.cc/projecthub/ronbentley1/button-switch-using-an-external-interrupt-7879df</a></p> <p>He does read the switch within the interrupt [I don't see why he needs to test the value since in his case it will always be HIGH]. The difference is that he uses the ISR only as a trigger. The rest of the reading of the switch to detect when there are state changes, is all done outside of the ISR.</p> <p>Additionally, once an interrupt occurs, a triggered status is set and, thereafter the ISR just leaves until the status is changed to &quot;not triggered&quot; and that is done outside of the ISR. The accompanying article explains what he is doing in the code and why.</p> <p>You are doing, literally nothing [after setup()] outside of the ISR and I think maybe you should re-think that approach.</p> <p>I tested his program and it works fine. I note that he functionally defines a &quot;press&quot; as pressing and releasing the button (with associated debouncing). So, you don't see the led toggle until you press and release the button. That's not always how I would like it, but it is also besides the point.</p> <p>Two other points...</p> <p>Keep your ISR as short as you can. I don't have any hard core evidence, but, right or wrong, yours looks longer than I would be comfortable with.</p> <p>Finally, I think you would enjoy this excellent thread on millis() inside an ISR. <a href="https://arduino.stackexchange.com/questions/22212/using-millis-and-micros-inside-an-interrupt-routine">Using millis() and micros() inside an interrupt routine</a></p> <p>To be sure, you are NOT using delays inside an ISR and there is nothing wrong with using millis() inside an ISR, but you need to be aware of the behavior.</p> <p>That's my two cents - hope it helps.</p>
91646
|esp8266|battery|mosfet|
ESP8266 Wemos D1 Mini Pro v2.0 - Load sharing and battery
2022-12-14T14:52:54.610
<p>I have a simple question regarding the new version of <strong>Wemos D1 Mini Pro v2.0</strong> and specifically about its load sharing circuitry. Schematic is here :</p> <p><a href="https://www.wemos.cc/en/latest/_static/files/sch_d1_mini_pro_v2.0.0.pdf" rel="nofollow noreferrer">https://www.wemos.cc/en/latest/_static/files/sch_d1_mini_pro_v2.0.0.pdf</a></p> <p>Battery charger is TP4054 and there's a load sharing configuration based on P-MOSFET CJ2301.</p> <p>My question is what happens if you do NOT connect any battery.</p> <p>It seems that the charging LED faintly flashes, and positive voltage appears in positive battery terminal. Moreover, voltage appears in A0 and ADC input (provided that SJ1 is connected), while someone would expect a zero voltage there, since there's no battery.</p> <p>Am I missing something here? Is there any way to fix this issue?</p>
<p>I have test it and you are right. When you plug power into the USB connector with no battery connected to the Wemos D1 mini Pro v2.0.0 (provided BAT-A0 is connected) and I have got 1023, the maximum read into A0, when it should be 0.</p> <p>I think a related problem is that when you are running with battery and you connect a charger into the USB port you can <em>not</em> read the battery voltage, you are getting always 1023, like if the battery was fully charged. So, you can use A0 to monitor battery voltage when discharging, but not when charging.</p>
91651
|c++|
A few Bitshifting questions!
2022-12-15T03:37:06.540
<p>So <code>int</code> in Arduino is 2 bytes, which could technically hold up to a value of 65535. However, the MSB is used as a sign bit, so now we have -32,768 to 32,767. So it's a <em>signed integer</em>, easy stuff. While I was messing around with bitshifting I ran across something interesting. If I do the following code:</p> <pre><code>int a = 1023 &lt;&lt; 6; // 1023 = 0b0000001111111111 Serial.println(a, BIN); </code></pre> <p>it returns a ridiculous number, 11111111111111111111111111000000, which is 4 bytes. I know this is some error with bit shifting into the signed bit, because if I do</p> <pre><code>int a = 1023 &lt;&lt; 5; // equals 111111111100000 as expected </code></pre> <p>It works just fine. <strong>Question 1:</strong> What is happening here? Where is that number coming from?</p> <p>So I got smart (so I thought) and was like okay, if I need more bytes, then I'll just use <code>long</code>. So I tried the following code:</p> <pre><code>long a = 1023 &lt;&lt; 6; Serial.println(a, BIN); </code></pre> <p>I figured I'd have 3 &quot;extra&quot; bytes to shift my number into. However, the same number is returned. <strong>Question 2:</strong> What is happening?</p> <p><strong>Question 3:</strong> What is the order of operations with bitshifting?</p> <pre><code>Wire.write(CMD_VDR | PD_NPD | voltageLevel &gt;&gt; 6); </code></pre> <p>This code I wrote produces the correct result. However, what is the order of operations? Is it just left to right? Putting <code>voltageLevel &gt;&gt; 6</code> in parenthesis does not change the output. <em>It's working fine but I want to know why!</em></p> <p>Thanks!</p>
<p>timemage provided an excellent answer to your first question (upvoted!). Let me try to answer the subsequent ones:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>long a = 1023 &lt;&lt; 6; </code></pre> </blockquote> <p>Here you are evaluating <code>1023 &lt;&lt; 6</code>, then assigning the result to a <code>long</code>. It is important to realize that the C++ rules for evaluating an expression do not depend on what you are going to do later with the result. Given that <code>1023</code> is an <code>int</code> constant, the expression has the type <code>int</code> and is evaluated as such. The result is then undefined behavior, which just happens, because <a href="https://www.nayuki.io/page/undefined-behavior-in-c-and-cplusplus-programs" rel="nofollow noreferrer">you are unlucky</a>, to give the expected value, i.e. −64.</p> <p>Assigning −64 to a <code>long</code> converts the type while preserving the value. This is <a href="https://en.wikipedia.org/wiki/Sign_extension" rel="nofollow noreferrer">sign extension</a> at work. As explained by timemage, <code>println(long, int)</code> casts the value to <code>unsigned long</code>, hence the result you see.</p> <blockquote> <p>What is the order of operations<br /> [in the expression <code>CMD_VDR | PD_NPD | voltageLevel &gt;&gt; 6</code>]?</p> </blockquote> <p>The shift has higher precedence than the bitwise OR. The expression is thus equivalent to</p> <pre class="lang-cpp prettyprint-override"><code>CMD_VDR | PD_NPD | (voltageLevel &gt;&gt; 6) </code></pre> <p>C.f. <a href="https://en.cppreference.com/w/cpp/language/operator_precedence" rel="nofollow noreferrer">C++ Operator Precedence</a>.</p>
91659
|arduino-uno|timers|code-review|continuous-servo|
Ramping servo motor taking longer than calculated
2022-12-15T16:49:46.530
<p>I'm learning how to code a &quot;BOE Shield bot&quot; with a partner at my university (first year). To clarify for those that do not know: a BOE Shield bot is a small robot equipped with 2 servo motors, a battery pack and an Arduino Uno. If you google the name you'll find plenty of pictures.</p> <p>We were tasked to code a program that would make the robot accelerate the continuous rotational servo motors according to a given velocity-time graph in RPMs and seconds. We wrote the code, followed a pretty logical method, and passed the assignment. However one thing, and I spent days on trying to fix it, is still confusing me. The code is ahead, I've tried to make it as readible as possible. The RPM to PWM conversion for the motors is: <br/> PWM = 2 \times RPM + 1500</p> <pre><code>#include &lt;Servo.h&gt; class motor { public: double Speed = 0; //The actual speed of the servo in RPM public: Servo servo; //returns true if the desired speed &quot;newSpeed&quot; is reached, otherwise increments the current speed and returns false. //increment is the calculated speed increase based on the differance in time (interval) and the acceleration which is constant. bool accel(double increment, double newSpeed) { if (abs(Speed - newSpeed) &lt; 0.1) { return true; } Speed += increment; return false; } void writeMS(double value) { servo.writeMicroseconds(value); } }; motor servoLeft = motor(); motor servoRight = motor(); void setup() { Serial.begin(9600); servoLeft.servo.attach(11); //vänster -2 * speedLeft + 1500 servoRight.servo.attach(10); //höger 2 * speedLeft + 1500 } //This nested array contains instructions for both servo motors: the desired speed, how long it should take to accelerate to it and how long //the instruction duration is. The first instruction starts from the second row. The first row is skipped and only used for calculations. //The columns are in the following order: {instruction length in ms, speed of the left motor in RPM, speed of right motor in RPM, acceleration time}. double instructions[7][4] = { { 0, 0, 0, 0 }, { 3000, 25, 25, 500 }, { 2550, 50, 10, 500 }, { 3000, 25, 25, 500 }, { 2850, 10, 50, 500 }, { 3000, 25, 25, 500 }, { 3000, 15, -15, 500 }, }; //time stuff unsigned long currentMillis; unsigned long previousMillis = 0; unsigned long lastInstructionMillis = 0; const double interval = 20; //i is the index for the instructions. int i = 0; bool updateL = false; bool updateR = false; //the speed increments for each servo. Calculated in the loop. double incrementL; double incrementR; void loop() { //This is to help keep track of the time so we can calculate the increments. It essentially means the speeds are only updated ever 20ms. currentMillis = millis(); if (currentMillis - previousMillis &gt;= interval) { previousMillis = currentMillis; //if the desired speed is reached, stop updating. This is just to optimize code. if (updateL) updateL = !servoLeft.accel(incrementL, instructions[i][1]); if (updateR) updateR = !servoRight.accel(incrementR, instructions[i][2]); } //this runs only once after each instruction. if (currentMillis - lastInstructionMillis &gt;= instructions[i][0]) { lastInstructionMillis += instructions[i][0]; i++; //exit program after all instructions have been completed. if (i == 7) exit(0); //the increments are calculated like such: increment = acceleration * interval //where constant acceleration = (newSpeed - oldSpeed) / accelerationTime incrementL = (instructions[i][1] - instructions[i - 1][1]) * interval / instructions[i][3]; incrementR = (instructions[i][2] - instructions[i - 1][2]) * interval / instructions[i][3]; updateL = true; updateR = true; } Serial.println((String)servoLeft.Speed + &quot; &quot; + (String)servoRight.Speed + &quot; &quot; + (String)currentMillis + &quot; &quot; + (String)i); //the actual ms signlas sent to the servos. servoLeft.writeMS(2 * servoLeft.Speed + 1500); servoRight.writeMS(-2 * servoRight.Speed + 1500); } </code></pre> <p>For some reason the acceleration is taking longer than specified in the instructions. For example, the first instruction specifies that both servos will accelerate from 0 to 25 RPM within 500ms. But printing out the speeds and time to the serial monitor shows that it actually takes around 860ms. That is if interval is set to 20. If it's set to 50, it takes 560ms.</p> <p>Suspected causes were:</p> <ol> <li><strong>Void loop taking longer than the interval</strong></li> </ol> <p>Not the case as measuring it with micros() proved it never took longer than 0.26ms; this was the done with complete program as well.</p> <ol start="2"> <li><strong>Rounding errors</strong></li> </ol> <p>Not the case as switching pretty much all the number types to double still didn't fix anything. And double is more than enough precise for this program.</p> <ol start="3"> <li><strong>millis() not being accurate enough</strong></li> </ol> <p>I don't believe this is the case. I researched how accurate it actually is, and while it's nowhere near perfect, it should be accurate enough for the program. I tried using micros() instead and that lead to the same result, I do not know if that means something.</p> <p>Other than that I have no idea what the cause could be. The code itself runs fine, and the robot actually seems to be following the instructions perfectly with no errors. It's just that the speeds and accelerations aren't accurate for some reason.</p>
<p>There are two things going on here.</p> <p>You are printing too much to the serial port. After the first second (between 1000 and 9999 ms), each line you print is 20 bytes, including the CRLF terminator. At 9600 b/s, each bytes takes 1.04 ms (1 start bit, 8 data bites and 1 stop bit). This is about 20.8 ms for the whole line, which is slightly longer than <code>interval</code>. You should either print less often (say, every other loop iteration) or faster. Just moving to the next standard speed (19200 b/s) will be enough to ensure you do not miss any <code>interval</code>. You can go faster though.</p> <p>The second issue is the way you keep track of <code>previousMillis</code>:</p> <pre class="lang-cpp prettyprint-override"><code>if (currentMillis - previousMillis &gt;= interval) { previousMillis = currentMillis; // ... } </code></pre> <p>This is prone to accumulating errors. The test will most likely not happen exactly at <code>previousMillis + interval</code>, mostly because of the serial port. You are a little bit late and, by updating <code>previousMillis</code> this way, these errors are <em>cumulative</em>. You can avoid this by updating <code>previousMillis</code> as:</p> <pre class="lang-cpp prettyprint-override"><code>previousMillis += interval; </code></pre> <p>You will still have timing errors, but these will manifest themselves in the form of <em>jitter</em>, not as a systematic timing drift.</p> <p>Interestingly, you are updating <code>lastInstructionMillis</code> the right way!</p> <hr /> <p><strong>Edit</strong>: Here are some extra comments about your question and your sketch, not necessarily related to the problem you are seeing.</p> <p>You wrote:</p> <blockquote> <p>measuring [loop()] with micros() proved it never took longer than 0.26ms.</p> </blockquote> <p>It seems you measured incorrectly. Maybe you measured a version of the program that was not printing so much to the serial port. Or maybe you looked only at the first iterations of the loop, where <code>Serial.println()</code> is fast because the output buffer hasn't filled yet.</p> <p>The following code is fragile:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>bool accel(double increment, double newSpeed) { if (abs(Speed - newSpeed) &lt; 0.1) { return true; } // ... } </code></pre> </blockquote> <p>The value 0.1 is arbitrary, and the “right choice” is dependent on the program timing. I suggest something more robust, like:</p> <pre class="lang-cpp prettyprint-override"><code>bool accel(double increment, double newSpeed) { if (increment &gt; 0) { Speed = min(Speed + increment, newSpeed); } else { Speed = max(Speed + increment, newSpeed); } return Speed == newSpeed; } </code></pre> <p>Note that, although it is generally recommended to not test floating point numbers for exact equality, in this case it is safe, because <code>min()</code> and <code>max()</code> return <em>exactly</em> one of their arguments.</p> <p>The optimization consisting of calling <code>motor::accel()</code> only during the acceleration phase is futile: this methods takes an very tiny fraction of the <code>loop()</code> time. In the same vein, there would be no harm in calling <code>Servo::writeMicroseconds()</code> on every loop iteration, even if some of the calls turn out to be useless.</p> <p>The code would be more readable if <code>instructions</code> was an array of <code>struct</code> rather than an array of arrays: this way the fields of each instruction could have evocative names rather than numeric indices.</p> <p>You are using too much floating point here. Most of the data fields, including all the contents of <code>instructions</code>, could be integers of suitable length.</p>
91670
|esp32|sleep|memory|deep|integer|
ESP32 can not deep sleep longer than 35 minutes
2022-12-17T15:57:57.443
<p>I'm trying to get my Lilygo T5 4.7&quot; epaper to deep sleep for 12 hours. But I only seem to be able to get about half an hour (2100s) of deepsleep on it. If I set the timer for longer, it just reboots right away.</p> <pre><code>#include &lt;Arduino.h&gt; #include &quot;epd_driver.h&quot; long DEEP_SLEEP_TIME_SEC = 43200; void start_deep_sleep() { epd_poweroff_all(); esp_sleep_enable_timer_wakeup(1000000L * DEEP_SLEEP_TIME_SEC); Serial.println(&quot;Starting deep-sleep period...&quot;); esp_deep_sleep_start(); } void setup() { Serial.begin(115200); Serial.println(&quot;\n- - - - - - - - -INITIALIZING - - - - - - - - - -&quot;); delay(10000); start_deep_sleep(); } void loop() { } </code></pre> <p>The sbove code gives the following:</p> <pre><code>16:44:25.104 -&gt; - - - - - - - - -INITIALIZING - - - - - - - - - - 16:44:35.105 -&gt; Starting deep-sleep period... 16:44:35.105 -&gt; ets Jul 29 2019 12:21:46 </code></pre> <ul> <li>and it just continues to reboot..</li> </ul> <p>Maybe I'm using the wrong variables in some way?</p> <p>Regards Kasper</p>
<p>So, formalizing this into an answer:</p> <pre class="lang-cpp prettyprint-override"><code>long DEEP_SLEEP_TIME_SEC = 43200; // ... esp_sleep_enable_timer_wakeup(1000000L * DEEP_SLEEP_TIME_SEC); </code></pre> <p>This is attempting to calculate the result of <code>1000000L * DEEP_SLEEP_TIME_SEC</code> as a <code>long</code> type because both operands are of <code>long</code> type. The language does not consider the values of the operands (your constant and variable) of an operator (the multiplication) when determining the type of the result (the product) nor what you do with the result after that (passing it to the function).</p> <p>The <code>long</code> type on ESP32 has a maximum value of 2147483647 which is as you said, &quot;about half an hour&quot; (not quite 36 minutes) worth of microseconds.</p> <p>According to the <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/sleep_modes.html#_CPPv429esp_sleep_enable_timer_wakeup8uint64_t" rel="nofollow noreferrer">documentation</a> <code>esp_sleep_enable_timer_wakeup</code> accepts a <code>uint64_t</code> type for its requested duration parameter. I don't know what the <em>valid</em> maximum value to call with is, but the original poster confirmed it was large enough for 12 hours.</p> <p>An <code>unsigned long long</code> is 64-bit on the ESP32 and the ULL suffix on <code>1000000ULL</code> forces the compiler to only consider types which are unsigned and which are not smaller than a long long. In practice it means make me an <code>unsigned long long</code> with value 1000000. In</p> <pre class="lang-cpp prettyprint-override"><code>esp_sleep_enable_timer_wakeup(1000000ULL * DEEP_SLEEP_TIME_SEC); </code></pre> <p>the compiler follows something called the <a href="https://en.cppreference.com/w/c/language/conversion" rel="nofollow noreferrer">usual arithmetic conversions</a> which will cause it to upconvert the <code>long</code> type of <code>DEEP_SLEEP_TIME_SEC</code> to match the <code>unsigned long long</code> that it is finding in <code>1000000ULL</code>. The multiplication is therefore carried out in the <code>unsigned long long</code> type, so that the calculation itself accommodates more microseconds than you'll ever know what to do with. What the actual maximum is for <code>esp_sleep_enable_timer_wakeup</code> is still unclear. If I find out I will update with that information.</p> <hr /> <p>The ESP32-Arduino support comes with a fairly complete C++ standard library. So, if you want to get fancy you can use the <code>&lt;chrono&gt;</code> <a href="https://en.cppreference.com/w/cpp/chrono/duration" rel="nofollow noreferrer">header</a>. Just to give an example of what that could look like in your context:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;chrono&gt; // ... static constexpr auto DEEP_SLEEP_TIME = std::chrono::hours{12}; // ... esp_sleep_enable_timer_wakeup( std::chrono::duration_cast&lt;std::chrono::microseconds&gt;( DEEP_SLEEP_TIME ).count() ); </code></pre> <p>I'm being very explicit in the above. But you can import parts of the chrono namespace so you don't have to name everything fully. <s>You can also import <a href="https://en.cppreference.com/w/cpp/chrono/operator%22%22s" rel="nofollow noreferrer">chrono literals support</a> so that you can use time constants that look more like natural language</s>(not yet apparently; there's still no C++14 support in Arduino-ESP32 I guess). You can control the underlying integer type used to represent the unit. It is also possible to create and name your own duration types to represent things like bit durations in a serial protocol etc. The default underlying type for <code>chrono::microseconds</code> is large enough for what you're doing; the default widths of underlying types are generally pretty sensible. Different time units are different <code>std::chrono</code> types so you can't mix them up accidentally. <code>duration_cast</code> is a means of explicit conversion of time units. The <code>.count()</code> in the above is just a way to get the raw integer value out of the chrono type for when you need to do that, like calling this function.</p> <p>If you wrap the function with your own taking <code>std::chrono::milliseconds</code> the unit conversion could just happen automatically in the call to your own wrapper:</p> <pre class="lang-cpp prettyprint-override"><code>static constexpr auto DEEP_SLEEP_TIME = std::chrono::hours{12}; //... esp_err_t esp_sleep_enable_timer_wakeup_using_chrono( std::chrono::milliseconds duration ) { return esp_sleep_enable_timer_wakeup( duration.count() ); } // ... esp_sleep_enable_timer_wakeup_using_chrono(DEEP_SLEEP_TIME); </code></pre> <p>The way durations work in chrono is such that you don't need to <code>duration_cast</code> when you're going to type that can represent the same values as the source type. The the prior example the point of the <code>duration_cast</code> was just so that <code>.count()</code> was getting a count of microseconds. In other words, the <code>duration_cast</code> performed the multiplication and would have selected a more appropriate underlying integer size. Here that conversion takes place during the call. Anyway, it may be worth some effort to learn about as it tends to help avoid problems with unit conversions and integer ranges.</p>
91685
|ds18b20|arduino-nano-rp2040|
DS18B20 temperature sensor crashes MbedOS on Arduino Nano RP2040?
2022-12-18T17:44:29.693
<p>I'm trying to use the DS18B20 sensor with Arduino Nano RP2040. No matter which library I use, it seems to crash MbedOS as soon as the driver is initialized. I get 4 short and 4 long flashes of the orange LED, which as I found somewhere indicates a crash.</p> <p>I was trying with DS18B20 library (<a href="https://github.com/matmunk/DS18B20" rel="nofollow noreferrer">https://github.com/matmunk/DS18B20</a>) as well as the DallasTemperature one (<a href="https://github.com/milesburton/Arduino-Temperature-Control-Library" rel="nofollow noreferrer">https://github.com/milesburton/Arduino-Temperature-Control-Library</a>).<br /> At first I suspected that the issue is in my code as it interfaces with multiple different devices (EEPROM, SHT30, etc.) and this may interfere with 1-wire interface, but if I upload just the examples from these libraries the effect is the same.</p> <p>I know that the Arduino is OK, as it can run other code absolutely fine, and the sensor is OK as well since I can read it with RaspberryPi.</p> <p>Does anyone have similar problems? Is there some workaround?</p>
<h4>Test Setup</h4> <p>I have wired an DS18B20+ to an RPI Pico and used a 4.7K pullup. The RPI Pico is a stand-in for your board. It uses the <code>arduino:mbed_rp2040:pico</code> core rather than the <code>arduino:mbed_nano:nanorp2040connect</code> that yours does. However, I'm guessing they're similar enough.</p> <h4>Test result</h4> <p>When I attempt the to use the <a href="https://github.com/matmunk/DS18B20" rel="nofollow noreferrer">matmonk DS18B20 library</a> you mention, I see similar pattern on the RPI Pico's onboard LED. Just the attempt to <a href="https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Single/Single.ino#L6" rel="nofollow noreferrer">construct the object</a> was sufficient to crash. Construction fairly directly <a href="https://github.com/matmunk/DS18B20/blob/1.0.0/src/DS18B20.cpp#L3-L6" rel="nofollow noreferrer">defers to the OneWire</a> library. So, I tried the OneWire library's own <a href="https://github.com/PaulStoffregen/OneWire/blob/v2.3.7/examples/DS18x20_Temperature/DS18x20_Temperature.ino" rel="nofollow noreferrer">example for reading the DS18B20</a> (with some appropriate modification) and it crashes in the same manner. This lead to searching for and finding issues for the RP2040 on the OneWire github page resulting in (among others) <a href="https://github.com/PaulStoffregen/OneWire/issues/105" rel="nofollow noreferrer">this find</a>. The answer mentions <a href="https://github.com/pstolarz/OneWireNg/" rel="nofollow noreferrer">OneWireNG</a>.</p> <h4>The OneWireNG <a href="https://github.com/pstolarz/OneWireNg/blob/0.12.2/examples/arduino/DallasTemperature/DallasTemperature.ino" rel="nofollow noreferrer">DallasTemperature example</a> works</h4> <p>Or rather, it's the library that works. But, this is the relevant example for it that works for me. I made the following modifications.</p> <ul> <li><p>All <code>Serial</code> usages were replaced with <code>SerialUSB</code> because I am using the USB connection for the Serial Monitor (well, a terminal emulator).</p> </li> <li><p>I changed the one wire object to use GPIO28 because it was conveniently close to the pins where I was picking up 3.3V and GND: <code>OneWire ds(28);</code></p> </li> </ul> <p><s>It seems plausible <strong>that you could change the <code>#include &lt;DS18B20.h&gt;</code> usages</strong> in the two libraries you cited to <code>#include &quot;OneWireNg_CurrentPlatform.h&quot;</code> and find that they then work fine. I have not tried this yet. If that's of particular interest to you I will try it and update</s>(<strong>Update below</strong>). However, this stock example from the OneWireNG library is not crashing and is printing temperatures that rise and fall expected when I manipulate the temperature of the sensor.</p> <h4>OneWireNg with Matmunk and DallasTemperature libraries</h4> <h5>In general</h5> <p>It turns out that it is <em>unnecessary</em> to modify libraries that were using the original OneWire, not even just changing the <code>#include</code>. Despite the OneWireNg example using <code>&quot;OneWireNg_CurrentPlatform.h&quot;</code> it also provides a OneWire.h header. It is sufficient to have OneWireNg installed but <strong>the original OneWire library must uninstalled</strong> (or moved out of the libraries directory) so as not to confuse the build process into selecting the original library based on the header name over the OneWireNg library. The OneWireNg authors may have used the OneWireNg specific header in the examples to avoid this problem wit their examples when both libraries were installed. They've gone out of their way to make it compatible with the original, but below are reports of specific tests with the two libraries mentioned anyway.</p> <h5>Matmunk library with OneWireNg</h5> <p>With OneWireNg installed and the original OneWire <em>not</em> installed, the <a href="https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Multiple/Multiple.ino" rel="nofollow noreferrer">Multiple example</a> form the matmunk library worked with the same minor modifications mentioned before (I used pin 28 rather than 2 and <code>SerialUSB</code> rather than <code>Serial</code>). In case your wondering the only reason why I switched from testing Single to Multiple is the latter didn't require that I first find and enter my part's address. That example is printing temperatures that rise and fall in accordance with manipulation of the sensor.</p> <h5>DallasTemperature with OneWireNg</h5> <p>Likewise I tested with the <a href="https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Multiple/Multiple.ino" rel="nofollow noreferrer">Multiple example from the DallasTemperature library</a>. Same kind of modifications to the example. I changed <code>ONE_WIRE_BUS</code> to <code>28</code> for my setup. I changed <code>Serial</code> to <code>SerialUSB</code>. And runs normally and prints expected temperatures under manipulation of the sensor.</p>
91706
|stepper|
Using a limit switch to stop a stepper motor
2022-12-20T16:21:21.520
<p>I am building a machine with a moving bed, the bed moves forward and backward. I need to incorporate a limit switch at the two ends that makes sure the motors stop at the two extremes. I have 2 stepper motors controlled by TB6600 motor drivers, I am trying to start with 1 limit switch (SS-5Gl2) and advance from there.</p> <p>My 1st question is how I get the code to stop steppers if limit switch is closed?</p> <pre><code>// Define stepper motor connections and steps per revolution: #define dirPin1 2 #define stepPin1 3 #define dirPin2 5 #define stepPin2 6 #define stepsPerRevolution 200 // We may need to change 200 to 1600 to get more precise control, i.e. decimals verse integers #define Lim1 8 int direction = 0; int remainder = 0; long travel = 0; long revolutions = 0; void setup() { // Declare pins as output: pinMode(stepPin1, OUTPUT); pinMode(dirPin1, OUTPUT); pinMode(stepPin2, OUTPUT); pinMode(dirPin2, OUTPUT); pinMode(Lim1, OUTPUT); //Desired travel distance, in mm !!!! set here !!!! travel = 1; //Desired direction !!!! set here !!!! move die in(ccw) = 1, back out(cw) = 0 !!!! //direction = 0; did not work, need boolean? // Set the spinning direction counterclockwise (die in) or clockwise (die out): //if(direction = 1) digitalWrite(dirPin, HIGH); //if(direction = 0) digitalWrite(dirPin, LOW); //set direction manually, uncomment HIGH for die in, LOW for die back out digitalWrite(dirPin1, LOW); digitalWrite(dirPin2, LOW); //digitalWrite(dirPin, LOW); digitalWrite(Lim1, OFF) // //calculating number of revolutions based on mm input. Does not yet account for partial revs - variable is truncated, integers are default. Would need another loop to handle the remainder //6.659 (microns) constant is based on 1.25mm acutator screw pitch, and ratio in gearbox revolutions = 1000.00*travel/6.659; //attempt to output the stored value to PC for debug purposes Serial.print(&quot;revolutions = &quot;); Serial.print(revolutions,4); } void loop() { // Spin the stepper motor X revolutions fast, speed (delay) apparently limited by voltage. 42v should go faster? //Required a nested loop because integers on the UNO are limited to ~32k for (int i = 0; i &lt; revolutions; i++) { if (digitalRead(Lim1 == OFF)){} else { for (int j = 0; j &lt; stepsPerRevolution; j++) { // These four lines result in 1 revolution: digitalWrite(stepPin1, HIGH); digitalWrite(stepPin2, HIGH); delayMicroseconds(250); digitalWrite(stepPin1, LOW); digitalWrite(stepPin2, LOW); delayMicroseconds(250); } } } while(1){} } </code></pre>
<pre><code>// Define stepper motor connections and steps per revolution: #define dirPin1 5 #define stepPin1 2 #define dirPin2 6 #define stepPin2 3 #define stepsPerRevolution 200 // We may need to change 200 to 1600 to get more precise control, i.e. decimals verse integers' #define limPin1 8 #define CW 0x1 #define CCW 0x0 int remainder = 0; long travel = 0; long revolutions = 0; bool homed = false; void setup() { // Declare pins as output: pinMode(stepPin1, OUTPUT); pinMode(dirPin1, OUTPUT); pinMode(stepPin2, OUTPUT); pinMode(dirPin2, OUTPUT); pinMode(limPin1, INPUT_PULLUP); //Desired direction !!!! set here !!!! move die in(ccw) = 1, back out(cw) = 0 !!!! //direction = 0; did not work, need boolean? // Set the spinning direction counterclockwise (die in) or clockwise (die out): //if(direction = 1) digitalWrite(dirPin, HIGH); //if(direction = 0) digitalWrite(dirPin, LOW); //set direction manually, uncomment HIGH for die in, LOW for die back out digitalWrite(dirPin1, LOW); digitalWrite(dirPin2, LOW); //attempt to output the stored value to PC for debug purposes Serial.begin(9600); Serial.println(&quot;test&quot;); } //main routine void loop() { Homing(); } void Homing() { // Spin the stepper motor X revolutions fast, speed (delay) apparently limited by voltage. 42v should go faster? //Required a nested loop because integers on the UNO are limited to ~32k if (homed == false) { //calculating number of revolutions based on mm input. Does not yet account for partial revs - variable is truncated, integers are default. Would need another loop to handle the remainder //6.659 (microns) constant is based on 1.25mm acutator screw pitch, and ratio in gearbox float travel = 2.0; float revolutions = 1000.00*travel/6.659; int totalStepsOut = revolutions * stepsPerRevolution; Serial.print(&quot;revolutions = &quot;); Serial.println(revolutions,4); digitalWrite(dirPin1, CCW); digitalWrite(dirPin2, CCW); for (int j = 0; j &lt; totalStepsOut; j++) { bool limState = digitalRead(limPin1); if (limState == false) { //Limit is triggered HomingReturn(); break; } else { //Limit is not triggered // These six lines result in 1 revolution: digitalWrite(stepPin1, HIGH); digitalWrite(stepPin2, HIGH); delayMicroseconds(250); digitalWrite(stepPin1, LOW); digitalWrite(stepPin2, LOW); delayMicroseconds(250); } } } //Add stuff here to do whatever you want after homing Serial.println(&quot;Homed&quot;); } void HomingReturn() { //set direction for reverse digitalWrite(dirPin1, CW); digitalWrite(dirPin2, CW); Serial.println(&quot;Reversing&quot;); //Desired travel distance, in mm !!!! set here !!!! float travel = 0.1; float revolutions = 1000.00*travel/6.659; int totalStepsOut = revolutions * stepsPerRevolution; for (int j = 0; j &lt; totalStepsOut; j++) { //drive back digitalWrite(stepPin1, HIGH); digitalWrite(stepPin2, HIGH); delayMicroseconds(250); digitalWrite(stepPin1, LOW); digitalWrite(stepPin2, LOW); delayMicroseconds(250); } homed = true; Serial.println(&quot;Done&quot;); } </code></pre>
91719
|esp8266|
Detecting the difference between a deep sleep wake signal and a manual wake button press
2022-12-21T16:40:55.087
<p>When my ESP8266 wakes itself from sleep (i.e. D0 sends wake signal), I want it to do something different to when I manually wake the device with the reset button.</p> <p>I have the RST and D0 pins connected, so that the device can wake itself from sleep. I also have a button connected to RST which pulls to ground when pressed, so that I can wake the device manually on demand.</p> <p>How do I differentiate between the device being awoken by itself, or manually by the button press?</p> <p>I tried using <code>system_get_rst_info</code>/<code>getResetInfoPtr</code> to determine what action has awoken the device, but it seems that if I reset manually after the device went to sleep, the <code>REASON_DEEP_SLEEP_AWAKE</code> reason is returned since that value is based on how the device went to sleep/reset rather than how it woke up.</p> <p>Disclaimer: I already found a solution (answer below), but it's more complex than I wanted, so I am posting this question to see if anyone else can think of a simpler solution.</p>
<p>I came up with two solutions (3 if you count the combo), both involve connecting the manual reset button to another pin on the MCU (so I can check if it's still pressed when starting).</p> <p><strong>Solution 1: Generate a reset pulse</strong></p> <p>The problem with the manual reset button is that it's only on release that it resets, since while the RST pin is held low, the MCU won't start.</p> <p>To solve this, I used a positive edge monostable circuit to pulse the RST pin when the manual reset button is pressed down.</p> <p>That way, I can hold the button down and the device starts. In the <code>setup()</code> function, I can check if the button is still pressed.</p> <p><strong>Solution 2: Use an RC delay circuit</strong></p> <p>I also considered that I could simply wake the device on button release, and use a debounce cap (very slow discharge) to see if the button was pressed in the last second (by checking the pin on the MCU to which the charged cap is connected).</p> <p><strong>Solution 3: A combination of 1 &amp; 2</strong></p> <p>Combining 1 and 2, allowed me to wake the device on button down, and use the debounce cap to see if the button was pressed recently (in the last second).</p> <p><a href="https://i.stack.imgur.com/rjXvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rjXvC.png" alt="Reset button circuit" /></a></p>
91735
|arduino-uno|sketch|code-review|temperature-sensor|dht11|
DHT11 temperature and humidity sensor Code
2022-12-23T15:23:33.240
<p>I’ve got a question about this code I’ve attached please- would it be correct to read it like this:</p> <p>After defining the variable temperature and humidity and assigning measurement_timestamp to millis(), an if loop first checks if millis - measurement_timestamp &lt; 3000 unsigned long (which doesn’t make sense to me) and then if a reading is read, it = true?</p> <p>Is this correct please?</p> <p>Code:</p> <pre><code>static bool measure_environment( float *temperature, float *humidity ) { static unsigned long measurement_timestamp = millis( ); /* Measure once every four seconds. */ if( millis( ) - measurement_timestamp &gt; 3000ul ) { if( dht_sensor.measure( temperature, humidity ) == true ) { measurement_timestamp = millis( ); return( true ); } } return( false ); } </code></pre>
<p>The code makes sense to me.</p> <p>The comment, &quot;/* Measure once every four seconds. */&quot; is inaccurate. It will measure when the time since last measurement is greater than 3 seconds.</p> <p>Because of &quot;static unsigned long measurement_timestamp = millis( );&quot;, measurement_timestamp will NOT be initialized to millis() every time the function is called - it will only be initialized once for lifetime of the run. Otherwise, it would never cause a measurement since &quot;if( millis( ) - measurement_timestamp &gt; 3000ul )&quot; would never be true.</p> <p>The first call sets measurement_timestamp= to millis() [the current timer value] and the function returns &quot;false&quot;</p> <p>When called 3.001 sec later, &quot;if( millis( ) - measurement_timestamp &gt; 3000ul )&quot; is true - a measurement is taken, &quot;measurement_timestamp&quot; is updated to the current millis() and the function returns &quot;true&quot;.</p> <p>It returns &quot;false&quot; for the next 3 seconds and then &quot;true&quot; and so on.</p> <p>see <a href="https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c">https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c</a></p> <p>and <a href="https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover">How can I handle the millis() rollover?</a></p> <p>Hope it helps.</p>
91766
|voltage|
Why 5V instead of 3V3?
2022-12-27T09:00:35.163
<p>I'm still quite new to electronics, so please forgive me if the answer is obvious.</p> <p>I was wondering why virtually all the example circuits I find use the 5V power supply with resistors for all the components instead of the 3V3 power supply directly.</p> <p>Even for the most simplistic &quot;Blink&quot; example, they use 5V pin and a 220 Ohm resistor to protect the LED instead of using the built-in 3.3V pin.</p> <p>Yes, I know that in former times &quot;everything&quot; ran on 5V, but since we already have a lower voltage built-in, why not use it and reduce the number of components needed?</p> <p>TIA for anyone who can solve this puzzle for me.<br /> mav</p>
<p>First, even with 3.3V, an LED needs a resistor to limit the current through it. So, running with 3.3V doesn't solve that particular problem. Try Googling for &quot;LED current limiting resistor&quot;.</p> <p>Second, many Arduinos are designed to run using 5V. In many cases they have an input power jack which can accept a range of voltages and use a voltage regulator to convert it down to 5V,</p> <p>Why not convert down to 3.3V you might ask? Well, the higher the voltage, the faster the processor can run, within its design limits. For example, the Atmega328P (which is in the Arduino Uno, and others) could only run at 13 MHz at 3.3V rather than 16 MHz.</p> <blockquote> <p>... instead of using the built-in 3.3V pin</p> </blockquote> <p>But that pin is only provided for convenience. You can't turn it on or off by a program.</p> <p>The higher voltage (5V vs 3.3V) can be more convenient in some situations, for example switching motors on and off, or with other devices designed to work with 5V.</p> <p>Motors or other high-power devices are typically turned on with MOSFET transistors. To be efficient, they need to fully turn on (have a low resistance between Source and Drain) and even so-called &quot;logic level&quot; MOSFETs typically require 5V to fully turn them on, rather than 3.3V. If you tried to control a motor with a 3.3V based board you would probably need extra components to turn the MOSFET on properly, so lowering the voltage could potentially add components, not reduce them.</p> <p>On the other hand, many components these days are designed to work with 3.3V (or lower) so the choice of 5V is a bit of a compromise.</p>
91768
|serial|arduino-nano|arduino-nano-ble|
Arduino nano 33 BLE serial port not working with C# app
2022-12-27T13:03:27.747
<p>I use an Arduino Nano with some sensors and send data to a PC using the serial port. I just got a new Arduino Nano 33 BLE and tried the same code but its not working. So for testing I just wrote some simple test code on the Arduino Nano 33 BLE side:</p> <pre><code>void setup() { Serial.begin(57600); } void loop() { if (Serial.available()) { char c = Serial.read(); Serial.write(c); } } </code></pre> <p>This just sends back whatever arrives through the COM port. Using the Arduino IDE Serial Monitor this works very well with the Arduino Nano 33 BLE. I also made this very simple C# test code (Windows Forms app):</p> <pre><code>SerialPort serialPort = new SerialPort(&quot;COM17&quot;, 57600); serialPort.ReadTimeout = 4000; serialPort.WriteTimeout = 4000; serialPort.Encoding = Encoding.ASCII; serialPort.DataReceived += SerialPort_DataReceived; serialPort.Open(); if (serialPort.IsOpen) { Debug.Print(&quot;COM port open&quot;); } </code></pre> <p>This C# code works perfect with my good old Arduino Nano but it doesn't work with the Arduino Nano 33 BLE. I have the <strong>COM port open</strong> message so the port exists and it is open, but then nothing else, no timeout, nothing. I already lost one day trying out all sorts of combinations but it just doesn't work, my C# app can't communicate with the Arduino Nano 33 BLE. It looks like a serial port issue so I think I'll put it on hold for now...</p> <p>EDIT: The rest of my test code, for reference:</p> <pre><code>private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { Debug.Print(serialPort.ReadExisting()); } catch (Exception exception) { Debug.Print(exception.Message); } } private void buttonSend_Click(object sender, EventArgs e) { try { serialPort.WriteLine(&quot;HELLO&quot;); } catch (Exception exception) { Debug.Print(exception.Message); } } </code></pre>
<p>I noticed that a lot of line discipline and flow control settings were not made explicit in your C# code, so it made me wonder what they were by default.</p> <p>In particular <code>DtrEnable</code> appears to be <a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.dtrenable?view=dotnet-plat-ext-7.0#system-io-ports-serialport-dtrenable" rel="nofollow noreferrer">false by default</a> and <code>Handshake</code> is None by default (which seems to be irrelevant). The other default amount to 8N1. The first part I found interesting because it seems more typical in serial APIs for DTR to be automatically asserted when a port is opened when you're not explicitly asking it to. If I'm reading the .NET documentation correctly, it isn't for your application. The original Nano doesn't much care about DTR apart from a falling edge triggering reset. The board is happy to communicate with it solidly either asserted or not. The original Nano's DTR is only capacitively coupled to reset; there's not a way for the code running on the AVR to respond to DTR (unless you count resetting). That lead to a question about to what extent a Nano 33 BLE would care about DTR.</p> <p>As it turns out the Nano BLE does care. If I deassert DTR in test with pyserial the board stops sending traffic back. I can write while it's deasserted and after asserting again some queued data arrives. <em>A test environment with pyserial is just more immediately available to me; if needed and I get a chance I'll set up a .net/C# test and confirm with that, but I suspect that won't be necessary.</em> Seeing that result, I searched and found <a href="https://forum.arduino.cc/t/cannot-read-write-using-3rd-party-terminal-to-arduino-nano-ble-board/642034" rel="nofollow noreferrer">this Arduino Forum post</a> with a somewhat similar problem description. The OP replies in answer to their own post saying:</p> <blockquote> <p>Problem sorted out. Arduino nano BLE requires DTR and RTS signals to be On. Then it works like FDTI.</p> </blockquote> <p>Disabling RTS had no effect during my tests with pyserial. I'm not sure why it would. Perhaps they just asserted it preemptively. Being entirely a virtual port RTS doesn't really make sense for flow control. DTR might arguably still makes more sense in this context; at the level of serial signals it normally tells you something is paying attention on the other side of the connection. I'm not really surprised, either way, that the BLE sense would react to DTR being disabled by not sending data to the host; there's a lot of latitude in how these signals can be handled. That it's not automatically used when the port is opened (or until specifically requested) seems <em>mostly</em> a C# thing. But it looks like the different handling of DTR between the two boards that is making your code work with one but not the other.</p> <p>So it would seem necessary and sufficient to add</p> <pre class="lang-cpp prettyprint-override"><code>serialPort.DtrEnable = true; </code></pre> <p>amongst your other settings following the opening of the port.</p> <p>If there's truth to what the Arduino Forum poster said about RTS, then you would also need</p> <pre class="lang-cpp prettyprint-override"><code>serialPort.RtsEnable = true; </code></pre> <p>but this is not indicated by the tests I've done (though again with pyserial).</p>
91770
|esp32|
Is there a schematic for the ESP32S Dev Kit C V4 NodeMCU WLAN Development Board?
2022-12-27T18:20:18.330
<p>Recently I bought a ESP32S Dev Kit C V4 NodeMCU WLAN Development Board. I got it from azdelivery.de in Germany. Now I am interested in the schematic for this board to learn more about it. Not Google, nor the support team at azdelivery.de could help me, but since the board is a Chinese mass product, I hope to find an answer here, where I could get the schematic. Thank you!</p> <p><a href="https://i.stack.imgur.com/2lZX4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2lZX4.jpg" alt="Picture" /></a></p>
<p>Espressif has schematics and more on their website. EZ-Delivery sells two different versions: One has a CP2101 USB-Interface, the other one uses a CH340 instead. If you have the CP2101 variant, this should match the one at Espressif's Website:</p> <p><a href="https://dl.espressif.com/dl/schematics/esp32_devkitc_v4-sch.pdf" rel="nofollow noreferrer">https://dl.espressif.com/dl/schematics/esp32_devkitc_v4-sch.pdf</a></p> <p>More related docs are linked on their Website (scroll down to &quot;Related Documents&quot; here:</p> <p><a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html#get-started-esp32-devkitc-board-front" rel="nofollow noreferrer">https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html#get-started-esp32-devkitc-board-front</a></p>
91777
|arduino-ide-2|
How to get rid of the second tab in Arduino IDE 2?
2022-12-28T12:17:55.337
<p>For a reason unknown to me, Arduino IDE 2.0.3 opens two tabs with the same name for this sketch. I'm not able to reproduce how to get into this situation.</p> <p>Changes in one tab immediately changes the other tab as well.</p> <p>How can I get rid of the second tab?</p> <p><a href="https://i.stack.imgur.com/FqcL3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FqcL3.png" alt="Duplicate tab" /></a></p> <p>Things I tried:</p> <ul> <li>File / Close (Ctrl+W) closes the whole sketch, i.e. Arduino IDE exists.</li> <li>The usual key combination to close tabs (Ctrl+F4) does not work either.</li> <li>I deleted all <code>%AppData%\Local\Temp\.arduinoIDE-unsaved*.gfv2</code> folders</li> <li>I deleted all <code>%AppData%\Local\Temp\arduino-sketch-*</code> folders</li> <li>I deleted all <code>%AppData%\Local\Temp\arduino-language-server*</code> folders</li> <li>I deleted all <code>%AppData%\Local\Temp\arduino-ide2-*</code> folders</li> <li>I used <a href="https://learn.microsoft.com/en-us/sysinternals/downloads/streams" rel="nofollow noreferrer">Streams</a> to check the INO file for alternate data streams</li> <li>I deleted the folder <code>%UserProfile%\.arduinoIDE</code></li> </ul> <p>Maybe interesting: when I rename the sketch to HelloWorld2.ino, it opens only one tab. If I rename it back, I have two tabs again.</p> <p>When I change the preferences to show the files in Sketchbook view, I only see one file: <a href="https://i.stack.imgur.com/WCJB9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WCJB9.png" alt="Sketchbook view" /></a></p> <p><sub>The other sketches have been created when trying to reproduce the problem. They are not affected</sub></p> <p>The tooltip which shows the full file name is identical on both files:</p> <p><a href="https://i.stack.imgur.com/f9q3c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f9q3c.png" alt="Identical tooltips" /></a></p> <p>The Registry does not contain suspicious information. I found only one occurrence of HelloWorld in</p> <pre><code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths </code></pre>
<blockquote> <p>How can I get rid of the second tab?</p> </blockquote> <ul> <li>Press <kbd>F1</kbd>,</li> <li>Type: <code>View: Reset Workbench Layout</code> into the <em>Command Palette</em>,</li> <li>Press <kbd>Enter</kbd>,</li> <li>IDE reloads.</li> </ul> <p>If it does not help, get the <a href="https://github.com/arduino/arduino-ide/blob/76f9f635d8558f399423f64c0c709e3a53bdcd03/arduino-ide-extension/src/browser/theia/core/shell-layout-restorer.ts#L23-L25" rel="noreferrer">layout data</a> from the logs.</p> <ul> <li>Open the DevTools with <kbd>Ctrl/⌘</kbd>+<kbd>Alt</kbd>+<kbd>I</kbd> <a href="https://github.com/eclipse-theia/theia/blob/7c559c87b3ffb0c7c3845309c20d3bf22529a076/packages/core/src/electron-browser/menu/electron-menu-contribution.ts#L340-L343" rel="noreferrer">built-in</a> command,</li> <li>Open the <em>Console</em> if it's not opened with <kbd>Esc</kbd>,</li> <li>Right-click in the console and <code>Save as...</code>,</li> <li>Share the data with the devs.</li> </ul> <p>For example:</p> <pre class="lang-json prettyprint-override"><code>{&quot;version&quot;:5,&quot;mainPanel&quot;:{&quot;main&quot;:{&quot;type&quot;:&quot;tab-area&quot;,&quot;widgets&quot;:[{&quot;constructionOptions&quot;:{&quot;factoryId&quot;:&quot;code-editor-opener&quot;,&quot;options&quot;:{&quot;counter&quot;:0,&quot;kind&quot;:&quot;navigatable&quot;,&quot;uri&quot;: ... </code></pre>
91788
|serial|arduino-ide-2|
How to fix the scambled output of the emojis in Arduino IDE 2?
2022-12-29T16:13:28.167
<p>I have relatively simple code printing some emojis:</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { // put your main code here, to run repeatedly: Serial.println(&quot;Hello world ❤‍♀️‍♂️✔&quot;); } </code></pre> <p>Just in case it doesn't render very well, here's an image on how it looks like in Arduino IDE 2.0.3:</p> <p><a href="https://i.stack.imgur.com/9AvLr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9AvLr.png" alt="Screenshot of code with emojis rendered" /></a></p> <p>However, the Serial Monitor sometimes displays emojis and sometimes not. It varies from line to line like so:</p> <pre class="lang-none prettyprint-override"><code>Hello world �����������������♀�������‍♂️✔���� Hello world ���������������‍♀️‍♂️✔ Hello world ��❤���������������������������������♂���✔ Hello world ❤‍�������‍������������� Hello world �������‍♀️��������������✔���� Hello world ��������������♀��������️����������� Hello world ��❤����������‍�����������♂�������✔��� </code></pre> <p>Again, there's how it looks like on my Windows 10 machine:</p> <p><a href="https://i.stack.imgur.com/qbR5l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qbR5l.png" alt="Screenshot of garbage output" /></a></p> <p>I verified that it's not a mistake in the baud rate. Both, Arduino and PC are set to 9600.</p> <p>In Arduino IDE 1, the output is not colorful and some emojis are not rendered at all, but the result is much more consistent:</p> <p><a href="https://i.stack.imgur.com/FYLnF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FYLnF.png" alt="Screenshot of output in Arduino IDE 1" /></a></p> <p>How to fix the scrambled output in Arduino IDE 2?</p>
<p>This is an issue of Arduino IDE 2.0.3. It was reported as <a href="https://github.com/arduino/arduino-ide/issues/589" rel="nofollow noreferrer">issue 589</a> and <a href="https://github.com/arduino/arduino-ide/issues/1405" rel="nofollow noreferrer">issue 1405</a>.</p> <p>It was fixed on 9th of December 2022 <a href="https://github.com/arduino/arduino-ide/pull/1758" rel="nofollow noreferrer">[PR]</a> and I can confirm it is fixed in nightly build 2.0.4-221229.</p>
91792
|arduino-ide-2|
How do I reset the recently used commands in Arduino IDE 2?
2022-12-29T22:54:53.950
<p>I am recording videos on Arduino IDE version 2. In one of the videos I want to explain how to enable a specific setting via the advanced properties. This requires using <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> (command palette).</p> <p>However, my Arduino IDE now shows some commands I have used recently (sorry, screenshot is in German).</p> <p><a href="https://i.stack.imgur.com/Rbybd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rbybd.png" alt="Arduino IDE 2 Command palette" /></a></p> <p>That's not the default. If someone has just installed Arduino IDE, he would need to scroll until he finds the entry. How do I reset the recently used items, so that I can record a proper video which requires scrolling?</p> <p>Resetting the workbench layout does not help.</p>
<ol> <li>open the command palette</li> <li>search and choose Preferences: Open Settings (UI)</li> <li>in the preferences window, search for the setting <code>workbench.commandPalette.history</code></li> <li>set that value to 0 and it will not save the recent commands</li> </ol>
91808
|programming|rtc|
is there Raw RTC output?
2022-12-31T19:17:22.400
<p>I have an I2C Real Time Clock, DS3231 RTC module , and I just want something like Unix Time. I'm using the uRTCLib, looking at the <a href="https://naguissa.github.io/uRTCLib_doc_and_extras/classuRTCLib.html#af8eea2501d6b82726ce6226529c82a89" rel="nofollow noreferrer">class methods</a> but dont see anything like that. I'm thinking there must be a raw read that would return all the digits. Is there an easy way to do that?</p>
<p>The DS3231 doesn't report the Unix time. It reports the current time in broken-down form (year, month... second). If you need Unix time, you have to compute it.</p> <p>I suggest using Adafruit's <a href="https://github.com/adafruit/RTClib" rel="nofollow noreferrer">RTClib</a>. This library implements the computation of Unix time, e.g.</p> <pre class="lang-cpp prettyprint-override"><code>uint32_t unix_time = rtc.now().unixtime(); </code></pre>
91819
|temperature-sensor|arduino-zero|oled|
Temperature is not updated on OLED screen - Grove components
2023-01-01T16:40:51.187
<p>I am using 2 grove components in order to display a temperature. I use an <a href="https://www.seeedstudio.com/Grove-I2C-High-Accuracy-Temperature-Sensor-MCP9808.html" rel="nofollow noreferrer">I2C High Accuracy Temperature Sensor - MCP9808</a> and an <a href="https://www.seeedstudio.com/Grove-OLED-Yellow-Blue-Display-0-96-SSD1315-V1-0-p-5010.html" rel="nofollow noreferrer">OLED Screen</a> using this script:</p> <pre><code>#include &lt;U8g2lib.h&gt; #include &lt;SPI.h&gt; #include &lt;Wire.h&gt; #include &quot;Seeed_MCP9808.h&quot; MCP9808 sensor; U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/SCL, /* data=*/SDA, /* reset=*/U8X8_PIN_NONE); //Software I2C char strTemp\[16\]; float temp; void setup() { u8g2.begin(); Serial.begin(115200); if (sensor.init()) { Serial.println(&quot;sensor init failed!!&quot;); } sensor.set_config(SET_CONFIG_ADDR, 0x0008); Serial.println(&quot;sensor init!!&quot;); } void loop() { sensor.get_temp(&amp;temp); Serial.print(&quot;temperature value is: &quot;); Serial.println(temp); delay(1000); dtostrf(temp, 7, 2, strTemp); u8g2.clearBuffer(); // clear the internal memory u8g2.setFont(u8g2_font_luBIS08_tf); // choose a suitable font u8g2.drawStr(0, 10, &quot;Hello Seeed!&quot;); // write something to the internal memory u8g2.drawStr(0, 30, &quot;Temp. value:&quot;); // write something to the internal memory u8g2.drawStr(0, 50, strTemp); // write something to the internal memory u8g2.sendBuffer(); // transfer internal memory to the display } </code></pre> <p>The temperature output is not updated on the screen and I think it might be related to I2C addresses. Is it possible?</p> <p>I run an I2C scanner and I think that the OLED address is 0x3C and the temp. sensor is 0x18. How can I assign them correctly. I never done something like that so any help is welcome.</p> <p>Thanks a lot.</p>
<p>You mix software I2C with hardware I2C on the hardware I2C pins.</p> <p>To use hw I2C with the display use the U8G2_SSD1306_128X64_NONAME_F_<strong>HW</strong>_I2C constructor.</p> <pre><code>U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE); </code></pre> <p>Or use a different pair of pins for the software I2C display control.</p>
91830
|c++|
How to abort compilation based on a "wrong" value in a variable
2023-01-02T13:21:31.847
<p>I looking for some code that can generate a compile time error when a variable contains a wrong value.</p> <p>I once started with this code in a c program:</p> <pre><code>#define FIFO_BUFFER_SIZE 8 #define FIFO_BUFFER_MASK ( FIFO_BUFFER_SIZE - 1 ) #if ( FIFO_BUFFER_SIZE &amp; FIFO_BUFFER_MASK ) #error Fifo buffer size is not a power of 2 #endif </code></pre> <p>Rewrote that in C++ for a PC console application:</p> <pre><code>MovingAVG::MovingAVG( const unsigned long element_count ) { ptr = 0; siz = element_count; buf = new long[siz]; msk = siz - 1; if( siz &amp; msk ) { //std::cerr &lt;&lt; &quot;Buffer size is not a power of 2&quot; &lt;&lt; std::endl; //exit( -1 ); } } </code></pre> <p>Now I want to use something similar in an Arduino sketch. Because there is not always a terminal connected to the serial port and exit() is useless in a microcontroller, I am looking for a way to abort compilation based on a value in a variable. I don't give myself much chance to find anything but to be absolutely sure that there is really no way, I am dropping the question here.</p> <p>I want to abort compiling (preferably with a message) when the parameter of a class-constructor contains an invalid value. Is that possible at all?</p> <p>Actually I want to see a message before I start programming the device. I have posted a possible solution below, that will throw a message during linking, but that only works when I declare the class with a constant parameter:</p> <pre><code>class MovingAVG avg( 32 ); </code></pre>
<p>As suggested by timemage, I think <code>static_assert()</code> is the right solution to your problem: it is the clearest and most semantically correct. The problem is, you cannot plug <code>static_assert()</code> directly into your code, as the expression you are testing is not a compile-time constant.</p> <p>I suggest you turn the argument of the constructor into a template argument. This will guarantee it is a compile-time constant. As a bonus, you will be able to use a statically-allocated buffer, which is nicer on the RAM than dynamic allocation:</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;int siz&gt; class MovingAVG { static const int msk = siz - 1; long buf[siz]; int ptr = 0; public: MovingAVG() { static_assert((siz &amp; msk) == 0, &quot;Element count should be a power of two.&quot;); } }; </code></pre> <p>This works:</p> <pre class="lang-cpp prettyprint-override"><code>MovingAVG&lt;32&gt; filter; </code></pre> <p>but this fails with “error: static assertion failed: Element count should be a power of two.”:</p> <pre class="lang-cpp prettyprint-override"><code>MovingAVG&lt;33&gt; filter; </code></pre>
91831
|arduino-uno|serial|atmega328|1-wire|
Curious Collision between OneWire and RadioHead
2023-01-02T13:49:44.597
<p>The code below runs on an Arduino Pro Mini (8MHz 328p) sending temperature readings using an inexpensive ASK transmitter. I use OneWire to read the DS18B20s, and RadioHead to manage the radio.</p> <p>The original problem was the send() calls at the top of the loop <em>always</em> worked, but the send() call in the temperature-reading loop <em>never</em> did.</p> <p>The fix was to insert a call to setModeTx() ahead of the send() call. I'm pleased it works, but it's a hollow victory because I can't figure out <em>why</em> it works.</p> <p>OneWire uses no timers and no interrupts. I wait for the temperature conversion using <code>_delay_ms()</code> which is a spin delay.</p> <p>I've read and re-read the OneWire and RH_ASK code and am still puzzled. Can anyone explain?</p> <p>Many thanks</p> <p>Here's the gist of the code…</p> <pre><code>RH_ASK radio(1024, 0, 10, 0, false); OneWire ow(2); void loop() { radio.send(/* build info */); // always works radio.send(/* battery health */); // always works ow.reset_search(); while (ow.search(addr)) { read_thermometer(addr); // the following send() works ONLY // when preceded by setModeTx() // It *never* works without it radio.setModeTx(); radio.send(/* one temp reading */); } } </code></pre> <p>UPDATE</p> <p>@timemage was correct in that there are also calls to Serial (which resolve to HardwareSerial) interspersed. I'm no closer to solving it; however, by rearranging calls I can get the failure to happen more- or less often.</p> <p>In a way this highlights the distinction between diagnosis and repair. I may in the end discover an ordering of the calls that makes the failure exceedingly rare, and in this case the problem will have been <em>repaired</em>; though not <em>diagnosed</em>.</p>
<p>Finally had time to get back to this. I connected the data-out line from the sender to the data-in line of the receiver, and discovered it always works. So it's <strong>not</strong> any sort of collision between OneWire and RadioHead, curious or otherwise. There's something amiss with the radio link… but what?</p> <p>Have a look at the following oscilloscope traces. The magenta line is the input to the transmitter. Cyan is the output from the receiver (an SYN480R if you're curious). Yellow is just there to trigger the scope (a digitalWrite() just before sending the problem message).</p> <p>The packet from the transmitter begins with a series of training pulses for the receiver to establish things like gain and threshold for the demodulator. Thereafter, the data is encoded in a series of long and short pulses.</p> <p>Note how the receiver (cyan line) syncs up with the training pulses, and is in lock-step with the transmitter... until ... IT GETS LOST and thinks everything is a zero for awhile. It eventually re-syncs with the transmitter, but by this point the packet is corrupt, gets rejected by the decoder, and <em>that</em> is why I'm losing the packet at the receiver.</p> <p><a href="https://i.stack.imgur.com/QTDGK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QTDGK.jpg" alt="enter image description here" /></a></p> <p>But, one wonders, why this particular packet and not any of the others? The answer to that question is pretty much out of band for a software forum, but here goes. Let's add a trace to the scope display.</p> <p>The following image includes the demodulator threshold in blue. That's an analog value that the demodulator uses to decide if it's looking at a one or a zero. For the SYN480R chip, it's the output of a low pass filter, which produces an <em>average</em> over the recent bits.</p> <p>In this case, notice how the threshold rises during the early part of the packet, then settles down. My conjecture is there are too many ones in the packet encoding thus far (i.e. many more ones than zeroes), and this shifts the threshold high enough that the demodulator thinks everything it sees is a zero. This is confirmed in the previous image. Seeing all zeroes, the threshold settles down and the demodulator can sync up again.</p> <p>Interestingly, just touching the scope probe to the threshold capacitor (to get the blue trace) disturbs the threshold enough to slow the rise and keep the packets working.</p> <p>Thus, OneWire is definitely off the hook, as is any interaction with RadioHead. Moving on, I either need to make some tweaks to the RadioHead RH_ASK driver packet encoder, or change out the threshold capacitor in the receiver. That in itself is a balance, because you want it to be able to track changes in the received signal, yet not be so sensitive to packet encoding.</p> <p>Hope you found this interesting. Many thanks to everyone who took a look and offered your insight.</p> <p><a href="https://i.stack.imgur.com/4JP41.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4JP41.jpg" alt="enter image description here" /></a></p>
91834
|arduino-uno|programming|c++|
Arduino code giving error while compiling
2023-01-02T23:51:41.787
<p>I am a beginner, and I'm trying to make code to control a servo using two ultrasonic sensors. I've tried to make the code, but when I tried to compile it using my simulation app, it gives this error:</p> <pre><code>sketch.ino: In function 'void value2()': sketch.ino:123:19: error: expected ')' before '!' token if((L &lt; R)&gt;=6 &amp; L !&gt; normal){ ^ sketch.ino: In function 'void value3()': sketch.ino:131:19: error: expected ')' before '!' token if ((R&lt; L)&gt;=6 &amp; R !&gt; normal){ ^ Error during build: exit status 1 </code></pre> <p>How do I go about fixing this? I'm using the Wokwi simulator website, and here is the <a href="https://wokwi.com/projects/352784217989806081" rel="nofollow noreferrer">link to the simulation</a>.</p> <p>Here is where the problem is in my code:</p> <pre class="lang-cpp prettyprint-override"><code>void value2() { /* I'm using L !&gt; normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */ if ((L &lt; R) &gt;= 6 &amp; L !&gt; normal) { servo.write(120); //goto loop(); } } void value3() { /* I'm using R !&gt; normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */ if ((R &lt; L) &gt;= 6 &amp; R !&gt; normal) { servo.write(60); //goto loop(); } } </code></pre> <p>And here is my complete code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Servo.h&gt; #include &lt;Stepper.h&gt; #define STEPS 100 // stepper steps #define speed 30 // stepper speed #define Lechopin 10 // ultrasonic sound sensor left #define Ltrigpin 11 // ultrasonic sound sensor left #define Rechopin 12 // ultrasonic sound sensor right #define Rtrigpin 13 // ultrasonic sound sensor right long Lduration; long Ldistance; long Rduration; long Rdistance; int L; int R; int dt1 = 100; //delay int dt2 = 1; //delay int dt3 = 2; //delay int dt4 = 10; //delay int serv = 9; //servo pin Servo servo; Stepper stepper(STEPS, 5, 6, 7, 8); /* Assuming distance of 4 feet measured by sensor is between 100 to 1000, let's set 750 as the normal distance between sensor and object in which will be anything in 4feet upward far away from sensor won't be detected by the code. you can edit it with real time measurement, I just assume this */ int normal=750; int minn=250; void setup() { Serial.begin(9600); stepper.setSpeed(speed); servo.attach(serv); pinMode(Lechopin,INPUT); pinMode(Ltrigpin,OUTPUT); pinMode(Rechopin,INPUT); pinMode(Rtrigpin,OUTPUT); } void loop() { get_L_dist(); L = get_L_dist(); get_R_dist(); R = get_R_dist(); normalp(); value1(); value2(); value3(); //bailout; } //print sensors /* Serial.print(&quot;L is:&quot;); Serial.println(L); Serial.print(&quot;R is:&quot;); Serial.println(R); */ /* read left sensor and calculate the distance */ long get_L_dist() { digitalWrite(Ltrigpin, LOW); delayMicroseconds(dt3); digitalWrite(Ltrigpin, HIGH); delayMicroseconds(dt4); digitalWrite(Ltrigpin, LOW); Lduration=pulseIn(Lechopin, HIGH); Ldistance=Lduration / 58.2; return Ldistance; } /* read right sensor and calculate the distance */ long get_R_dist() { digitalWrite(Rtrigpin, LOW); delayMicroseconds(dt3); digitalWrite(Rtrigpin, HIGH); delayMicroseconds(dt4); digitalWrite(Rtrigpin, LOW); Rduration=pulseIn(Rechopin, HIGH); Rdistance=Rduration / 58.2; return Rdistance; } //normal position of servo void normalp() { if (L &gt;= normal &amp; R &gt;= normal) { servo.write(90); //goto loop(); } } void value1() { if ((L &lt; minn) &gt;= 2 &amp; (R &lt; minn) &gt;= 2) { int ran = random(2); if (ran == 0) { servo.write(30); //goto loop(); } if (ran == 1) { servo.write(150); //goto loop(); } } } void value2() { /* I'm using L !&gt; normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */ if ((L &lt; R) &gt;= 6 &amp; L !&gt; normal) { servo.write(120); //goto loop(); } } void value3() { /* I'm using R !&gt; normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */ if ((R &lt; L) &gt;= 6 &amp; R !&gt; normal) { servo.write(60); //goto loop(); } } </code></pre>
<p>Use <code>&lt;=</code> instead of <code>!&gt;</code>; the latter is not proper C++ syntax.</p> <p>Also, <code>if (L &lt; R) &gt;= 6</code> doesn't do what you may think: <code>(L &lt; R)</code> evaluates to <code>true</code> or <code>false</code>, so the whole expression will always evaluate to <code>false</code>. Did you mean <code>if (L - R) &gt;= 6</code> maybe?</p> <p>Also, you use <code>&amp;</code> as an &quot;and&quot; in your <code>if</code> statements, which should be <code>&amp;&amp;</code>.</p>
91842
|c++|iot|json|mqtt|
how to transfer json to string?
2023-01-03T09:35:23.840
<p>I am getting a json object from aws iot MQTT. Assuming that json from aws is {status:opened}. Here is my code.</p> <pre><code>#include &lt;ArduinoJson.h&gt; void messageHandler(char *topic, byte *payload, unsigned int length) { StaticJsonDocument&lt;32&gt; doc; deserializeJson(doc, payload); const char *status = doc[&quot;status&quot;]; Serial.println(status);//opened if (status == &quot;opened&quot;) { Serial.println(&quot;door is opened&quot;);//not excute } else if (status == &quot;closed&quot;) { Serial.println(&quot;door is closed&quot;); } } </code></pre> <p>Why the if condition is not being excute?</p>
<p>That's one of the peculiarities of the C language: the <code>==</code> operator compares the string addresses, not their content. It makes sense when you think of them as pointers, but it can be confusing for beginners.</p> <p>To fix this, you can use <code>strcmp()</code> like so:</p> <p><code>if (strcmp(status,&quot;opened&quot;) == 0)</code></p> <p>Alternatively, you can change the type of <code>status</code> to <code>JsonVariant</code>, like so:</p> <p><code>JsonVariant status = doc[&quot;status&quot;]</code></p> <p>It works with <code>JsonVariant</code> because I overloaded the <code>==</code> operator to support string comparison.</p>
91854
|usb|attiny|attiny85|
Alternate full speed usb library for ATTINY85?
2023-01-04T02:15:31.073
<p>I'm currently working on a project using the ATTINY85 for USB communication. After some research, it turns out that the V-USB library only supports usb 1.1, which only supports a 125hz polling rate. I would like to be able to have a polling rate of 1000hz, or close to it, which requires usb 2.0 or faster. I was hoping that someone could help point me to a library which supports usb 2.0, or suggest an alternative. Any help would be greatly appreciated, thanks in advance!</p>
<p>Since an ATtiny85 has no built-in USB hardware module, you use a software solution like V-USB. Unfortunately bit-banging software cannot be as fast as hardware, so you are out of luck here. (Reading the documentation of V-USB is enlightened and explains the difficulties and limits of such a solution.)</p> <p>You cannot have USB 2.0 with an ATtiny85 alone.</p> <p>Possible solutions:</p> <ul> <li>an external USB module</li> <li>another microcontroller</li> </ul>
91862
|arduino-nano|digital|rotary-encoder|breadboard|
Rotary encoder weird values
2023-01-04T15:57:37.477
<p>I am trying to understand this rotary encoder I have, but it makes no sense to me.</p> <p>I am using this rotary encoder: <a href="https://rads.stackoverflow.com/amzn/click/com/B07DM2YMT4" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/gp/product/B07DM2YMT4/</a></p> <p>CYT1100 aka CY110 aka EC11</p> <p>I am using this wiring: <a href="https://i.stack.imgur.com/aMyR5.png" rel="nofollow noreferrer">https://i.stack.imgur.com/aMyR5.png</a></p> <p>P2 is the &quot;push button&quot; and it gives continuity when pressed.</p> <p>I am using a knock off arduino nano and this is my simple script:</p> <pre><code>#define PIN_CLK 2 void setup() { Serial.begin(9600); pinMode(PIN_CLK, INPUT); } void loop() { auto val = digitalRead(PIN_CLK); Serial.println(&quot;CLK:&quot; + String(val)); } </code></pre> <p>Where PIN_CLK is connected to A (DW) or B (CLK) in the diagram.</p> <p>My expectation is that A and B should be either a constant HIGH or LOW depending on where the brushes are internally. Not switching to HIGH or LOW for a moment and then returning to what it was before.</p> <p>When I check them with my multimeter, they are both always 5v (when its not making loose contact on the breadboard).</p> <p>The serial plotter says its switching between HIGH and LOW repeated:</p> <p><a href="https://i.stack.imgur.com/6VC3z.png" rel="nofollow noreferrer">https://i.stack.imgur.com/6VC3z.png</a></p> <p>Same with the Serial monitor:</p> <p><a href="https://i.stack.imgur.com/wAk0v.png" rel="nofollow noreferrer">https://i.stack.imgur.com/wAk0v.png</a></p> <p>When I spin the encoder, it gives me gaps of LOW in the output like this:</p> <p><a href="https://i.stack.imgur.com/lOUmx.png" rel="nofollow noreferrer">https://i.stack.imgur.com/lOUmx.png</a></p> <p>If I hold my index and thumb against P1 (5v) and A (CLK) while spinning the encoder. I get constant stream of HIGH with a LOW on every notch spin:</p> <p><a href="https://i.stack.imgur.com/CzUwV.png" rel="nofollow noreferrer">https://i.stack.imgur.com/CzUwV.png</a></p> <p>Can someone explain this behavior and how this encoder is suppose to work?</p> <p>Edit: I tried this schematic:</p> <p><a href="https://i.stack.imgur.com/Mlj1l.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Mlj1l.png</a></p> <p>Whenever I turn the encoder. The LED blinks for a few milliseconds. Then turns off.</p> <p>Is it suppose to stay solid depending on the 2 bit states?</p> <p>Edit2: If I turn it extremely slowly. It turns the leds on in the order of left right or right left depending on the direction.</p> <p>So the led diagram above works, but its weird to me.</p>
<p>When encountering weird values from a <a href="https://indmall.in/rotary-encoders-with-arduino/" rel="nofollow noreferrer">rotary encoder</a>, there are a few possible reasons and troubleshooting steps you can take:</p> <p><strong>Mechanical issues:</strong> Check if there is any physical damage or obstruction affecting the rotary encoder's movement. Ensure that it rotates smoothly without any unusual resistance or skips.</p> <p><strong>Loose connections:</strong> Verify the wiring connections between the rotary encoder and the device it is connected to. Ensure that the connections are secure and properly seated.</p> <p><strong>Electrical noise:</strong> Electrical noise or interference can sometimes cause erratic readings. Try using shielded cables for the connections and consider adding capacitors or ferrite beads to filter out noise.</p> <p><strong>Incorrect configuration:</strong> Review the setup and configuration of the rotary encoder in your code or software. Make sure that you have selected the correct type of encoder (incremental or absolute) and that the signal processing is correctly implemented.</p> <p><strong>Debouncing:</strong> If you are using an incremental rotary encoder, it may produce multiple pulses or bouncing signals when rotating. Implementing debouncing techniques in your code can help filter out these erroneous readings.</p> <p><strong>Resolution and speed settings:</strong> Check if the resolution and speed settings in your code or software match the specifications of your rotary encoder. Incorrect settings can lead to unexpected values.</p> <p><strong>Compatibility issues:</strong> Ensure that the rotary encoder you are using is compatible with the device or system you are connecting it to. Check the specifications and requirements of both the encoder and the device to ensure compatibility.</p> <p>If you have gone through these troubleshooting steps and are still experiencing weird values from your rotary encoder, it might be worth considering a replacement or consulting the manufacturer's support for further assistance.</p>
91869
|arduino-uno|library|keypad|
Making library for arduino
2023-01-05T10:35:43.403
<p>I'm learning library making on arduino , I want to make a library that works with arrays a user sets, e.g:</p> <p>User sets array of int, when a certain function is been called the library will check if some instance are true or not ann set the return function accordingly as the array.</p> <p>Code example:</p> <pre><code> //in project example #include &lt;Keyss.h&gt; int rows=4; int cols=2; int a=0; int b=1; int c=2; int inp=3; int keyss[4][2]={ {0,1},, {2,3}, {4,5}, {6,7} }; Key key((keyss),rows,cols,inp,a,b,c); void setup(){ Serial.begin(9600); int keyprint=key.getkey(); Serial.println(key print); } void loop(){ } </code></pre> <p>And this will be the library files Keys.h</p> <pre><code> #ifndef KEYSS_H #define KEYSS_H #include &lt;Arduino.h&gt; class Key { public: Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3); int getkey(); int waitforkey(); private: int *_keys; int _rows; int _cols; int _inp; int _t1; int _t2; int _t3; }; #endif </code></pre> <p>And Keys.CPP</p> <pre><code> #include &lt;Keyss.h&gt; //initialization Key::Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3){ _keys=keys[4]; _rows=rows; _cols=cols; _inp=inp; _t1=t1; _t2=t2; _t3=t3; pinMode(_inp,INPUT); pinMode(_t1,OUTPUT); pinMode(_t2,OUTPUT); pinMode(_t3,OUTPUT); } //getkey() int Key::getkey(){ int _a; int _b; int _i=0; int _keymap=false; int _val; int _dt=500; int _s1; int _input; for(_a=0;_a&lt;_rows;_a++){ for(_b=0;_b&lt;_cols;_b++){ _s1=_i; digitalWrite(_t1,(_s1&gt;&gt;0)&amp;1); digitalWrite(_t2,(_s1&gt;&gt;1)&amp;1); digitalWrite(_t3,(_s1&gt;&gt;2)&amp;1); delayMicroseconds(_dt); _input=digitalRead(_inp); if(_input==true &amp;&amp; _keymap==false){ _val=_keys[_a*_cols+_b]; _keymap=true; } _i++; } } if(_keymap==false){ _val=-1; } return _val; } //waitforkey() int Key::waitforkey(){ int _waitfor=getkey(); while(_waitfor&lt;0){ _waitfor=getkey(); } return _waitfor; } </code></pre> <p>Where I have problem now is I don't know how to use or assign an array in a library I don't know how to use functions to refer to an array a user inputes, like here</p> <pre><code>int keyss[4][2]={ {0,1}, {2,3}, {4,5}, {6,7} }; </code></pre> <p>How do I use a function or inside the library to refer to the array a user sets?</p> <p>Please how do I achieve that?</p> <p>Its giving this error <a href="https://i.stack.imgur.com/8J3Up.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8J3Up.jpg" alt="error message" /></a></p>
<p>Your <code>keys</code> variable is a 2D array of <code>int</code>, i.e. it is an array of arrays. In C++, when an array is assigned to a variable or passed as an argument, it implicitly decays to a pointer to its first element. Note, however, that the decay-to-pointer behavior is not recursive. In this case you end up with a pointer to an array of three <code>int</code>.</p> <p>Your code should work if you give the proper type to the <code>_keys</code> class member and the <code>keys</code> constructor parameter:</p> <pre class="lang-cpp prettyprint-override"><code>class Key { public: Key(int (*keys)[3], int trig1, int trig2, int trig3, int inpin); int getkey(); private: int (*_keys)[3]; // pointer to array of 3 int. int _trig1; int _trig2; int _trig3; int _inpin; int _keye; }; </code></pre> <hr /> <p><strong>Edit</strong>: You have completely changed the question, to the point that my answer may not be relevant anymore. In the previous version of the question, it looked like you wanted to use a 3×3 2D array of numbers in the class. In the current version, you are using an array of arbitrary sizes represented as a flattened 1D array. These are quite different approaches.</p> <p>If you want to use a 2D array, the number of <em>columns</em> has to be a compile-time constant. You have to declare the member variable as a pointer-to-array like this:</p> <pre class="lang-cpp prettyprint-override"><code>int (*_keys)[2]; // there are two columns, not four! </code></pre> <p>assign it like this:</p> <pre class="lang-cpp prettyprint-override"><code>_keys = keys; // do NOT subscript keys </code></pre> <p>and use it like this:</p> <pre class="lang-cpp prettyprint-override"><code>_val = _keys[_a][_b]; // it is a 2D array </code></pre> <p>This approach cannot work if you do not know the number of columns beforehand.</p> <p>If you want to use a flattened (1D) array, then the parameter of the constructor has to be a simple <code>int*</code>, and you have to give it the address of the first element of the original 2D array:</p> <pre class="lang-cpp prettyprint-override"><code>Key key(&amp;keyss[0][0], rows, cols, inp, a, b, c); </code></pre> <p>The drawback of using a flattened array is that, in order to access the elements, you have to perform explicit index calculations:</p> <pre class="lang-cpp prettyprint-override"><code>_val = _keys[_a*_cols + _b]; </code></pre>
91871
|voltage-level|voltage|pulsein|
How to trigger a function by detecting voltage change?
2023-01-05T14:05:41.157
<pre><code>#define monitor_pin 14 void setup() { pinMode(monitor_pin , INPUT); } void loop() { unsigned long d1 = pulseIn(14, HIGH); if (d1&gt;0){//trigger function} } </code></pre> <p>I know there is a function pulseIn(), but it doesnt really solve my problem. I just want to trigger a function when voltage change from LOW to HIGH/HIGH to LOW. pulseIn() need to wait for the voltage to back to original level which in my case will exceed 3 minutes and cause timeout.</p> <p>How can I detect a voltage change other than pulseIn()?</p>
<p>You can save the previous state of the pin and then trigger the function when the current state is different from the previous state:</p> <pre><code>#define monitor_pin 14 int previous_state; void setup() { pinMode(monitor_pin , INPUT); previous_state = digitalRead(monitor_pin); // Initialize previous state with initial reading of the pin } void loop() { int current_state = digitalRead(monitor_pin); if(current_state != previous_state){ // Execute your code here previous_state = current_state; // update previous state } } </code></pre>
91900
|arduino-uno|serial|esp32|atmega328|softwareserial|
SoftwareSerial will not read all of the printed string when calling readString()
2023-01-08T17:55:43.157
<p>I have an Arduino UNO and an ESP32 that need to communicate to each other using SoftwareSerial. The problem I am coming across is that when I call readString and print it out using Serial, it will not give me everything that has been printed out from my ESP32.</p> <p>I have my Arduino RX Pin hooked up to 4 and TX hooked up to 5 I have my ESP32 RX2 Pin hooked up to 16 and TX2 pin hooked up to 17, with the GND hooked up to directly to the Arduino GND I am not using any resistors, straight up 5v of pure power</p> <p>Arduino UNO Code:</p> <pre><code>// C-standard library #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; #include &lt;SoftwareSerial.h&gt; #define RX_PIN 4 #define TX_PIN 5 SoftwareSerial ardSerial(RX_PIN, TX_PIN); void setup(void) { // Get access to network pinMode(RX_PIN, INPUT); pinMode(TX_PIN, OUTPUT); Serial.begin(9600); while(!Serial) {} ardSerial.begin(9600); while(!ardSerial) {} } void loop(void) { while (ardSerial.available() &gt; 0) { String payload = ardSerial.readString(); Serial.println(payload); } delay(1000); } </code></pre> <p>ESP32 Code</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;SoftwareSerial.h&gt; SoftwareSerial ardSerial; void setup(void) { // Begin connections Serial.begin(115200); while (!Serial) {} ardSerial.begin(9600, SWSERIAL_8N1, RX2_PIN, TX2_PIN); while (!ardSerial) {} return; } void loop(void) { { String spotData = &quot;Huge JSON File that needs transferred&quot;; ardSerial.print(spotData); } delay(5000); } </code></pre> <p>Expected result:</p> <ul> <li>Able to retrieve every little bit of the JSON file that was printed out</li> </ul> <p>Actual result:</p> <ul> <li>Only receive like half of the JSON file</li> </ul>
<p>There are two ways to implement a parser for a language like JSON or XML:</p> <ol> <li><p>Have the parser swallow the whole document at once, and produce an in-memory representation of the same data.</p> </li> <li><p>Have the parser return control to the caller for each “event” it detects, where an “event” is typically a primitive data item, or the start or the end of a container.</p> </li> </ol> <p>Parsers of the first kind are much easier to use, but this can be expensive in RAM usage if you want to parse a alrge document. The second kind of parsers are harder to use, but they are able to parse huge documents using a minimal amount of memory.</p> <p>On an Arduino, you would typically use ArduinoJson, which is a parser of the first kind, not ideal for parsing huge documents on little memory. A quick search for “event driven C++ JSON parser” got me <a href="https://github.com/xquintana/JsonReader" rel="nofollow noreferrer">JsonReader</a>. I did not try it, and do not know whether that would work on Arduino, but it shows that at least this kind of parsers do exist for JSON in C++. You may want to search further along this way.</p> <p>Before you dig into this, however, I suggest you give ArduinoJson a second chance. ArduinoJson has a couple of tricks that can help dealing with large documents:</p> <ul> <li><p>You can ask it to filter the data as it reads it, in order to only keep in memory the items you are actually interested in.</p> </li> <li><p>You can deserialize in chunks, and use the data extracted from one chunk at a time.</p> </li> </ul> <p>Both techniques are explained in the tutorial <a href="https://arduinojson.org/v6/how-to/deserialize-a-very-large-document/" rel="nofollow noreferrer">How to deserialize a very large document?</a>.</p> <p>Also, let's not forget the obvious: you should not attempt to store the raw JSON document in memory. Instead, you should give ArduinoJson a reference to your stream (namely <code>ardSerial</code>), and let it directly pull the bytes as it parses.</p>
91909
|arduino-ide|library|arduino-ide-2|
Just installed Arduino 2.0.3 - what is windows path to associated libraries?
2023-01-08T23:31:38.480
<p>Just installed Arduino 2.0.3 and I attempted to build a sketch which includes a library that I manually installed in version 1.8.19 and it can't be found:</p> <p>In my program I have <code>#include &lt;DS3231.h&gt;</code></p> <p>Now, attempting to compile it cannot find the library.</p> <p>What is the path to the basic libraries in Arduino 2.0.3?</p>
<p>I found the location by examining the app while it was running.</p> <p>The associated libraries are at:</p> <p><code>%localappdata%\arduino15\Libraries</code></p> <p>That will look like : <code>C:\Users\&lt;username&gt;\AppData\Local\Arduino15\libraries</code></p> <p>I created a new folder named <code>DS3231</code> dropped in the .cpp, .h and .config files and now my sketch compiles with the <code>#include &lt;DS3231.h&gt;</code></p> <p>Kind of blows my mind that the Arduino 2.0.3 Libraries are found in a directory named Arduino15. Is that an old version or something?</p> <p>Here's what I see in preferences -- don't see a location for user libraries:</p> <p><a href="https://i.stack.imgur.com/4Sptg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Sptg.png" alt="arduino preferences" /></a></p> <p>The best location will be your sketchbook location + a folder named <code>libraries</code>.</p> <p>For example, in my case my sketchbook location is :</p> <p><code>c:\users\&lt;username&gt;\dev\arduino</code></p> <p>so my library folder should be:</p> <p><code>c:\users\&lt;username&gt;\dev\arduino\libraries</code></p>
91915
|arduino-uno|arduino-mega|interrupt|atmega328|timers|
Arduino nano timing precision
2023-01-09T14:53:59.993
<p>How precisely can an Arduino nano be timed? The project I am working on needs two Arduino nano to work synchronously. Arduino one have to activate a relay after 2700 sec and Arduino two have to activate a second relay after 2700.360 sec (360 milli seconds after )</p> <p>With the code given below the required accuracy is not achieved.</p> <pre><code>volatile uint32_t ovfCount = 0UL; volatile uint32_t currentTime = 0UL; volatile unsigned long time_prev = 0UL; volatile unsigned long dT = 0UL; unsigned long delayTime = 2700UL; //Seconds unsigned long coilActivateTime = 5UL; // seconds volatile unsigned long _waitTime = delayTime * 1000UL + 360UL; uint32_t _burnTime = coilActivateTime * 1000UL; volatile bool coilOn_flag = false; ISR(INT0_vect) { EIMSK = 0b00000000; TCCR1B = B00011100; PORTB ^= (1&lt;&lt;0); ovfCount = 0; TIFR2 = 0; TCNT2 = 0; } ISR(TIMER2_OVF_vect) { ovfCount++; } ISR(TIMER1_OVF_vect) { //pass } ISR(TIMER1_COMPA_vect) { //pass } ISR(TIMER1_COMPB_vect) { uint8_t tcnt2 = TCNT2; uint32_t ovf_count = ovfCount; if (bit_is_set(TIFR2, TOV2) &amp;&amp; tcnt2 &lt; 128) { ovf_count++; } uint32_t totalCount = ovf_count &lt;&lt; 8 | tcnt2; // raw count // uint32_t currentTime = totalCount * 0.004; // milli second currentTime = totalCount * 4UL/1000UL; // milli second if (currentTime &gt;= _waitTime) { PORTC ^= (1 &lt;&lt; 5); // relay Switch TCCR1A = B00000010; TIMSK1 = B00000101; PORTB |= (1&lt;&lt;1); if (coilOn_flag) { TCCR1B = 0; PORTB ^= (1 &lt;&lt; 1) | (1&lt;&lt;0); } coilOn_flag = true; _waitTime = _burnTime; ovfCount = 0; TCNT2 = 0; } } void setup() { Serial.begin(115200); /*setting the pin directions*/ DDRB |= (1 &lt;&lt; 1) | (1 &lt;&lt; 0); // gL, rL DDRC |= (1 &lt;&lt; 5); // relay DDRD &amp;= B11111011; // interrupt- interrupt /* INITIAL STATE SETTING FOR THE PINS */ PORTB &amp;= B11111100; // rL, gL PORTC &amp;= B11011111; // relay /* 8Bit Timer*/ TCCR2A = 0; TCCR2B = 0; TCCR2A = B00000011; TCCR2B = B00001100; OCR2A = 250; TCNT2 = 0; TIFR2 = 0; TIMSK2 = B00000001; /* 16 bit timer */ TCCR1A = 0; TCCR1B = 0; TCCR1A = B10000010; // TCCR1B = B00011100; TCCR1B = 0; ICR1 = 62461; OCR1A = 6206; OCR1B = 624; TCNT1 = 0; TIFR1 = 0; TIMSK1 = B00000111; /* External INTERRUPT */ EICRA = 0b00000010; EIFR = 0; EIMSK = 0b00000001; PORTB ^= (1&lt;&lt;0); } void loop() { } </code></pre> <p>How to correct the code.?</p>
<p>The Arduino Nano is nowhere accurate enough for your application, and this has nothing to do with your code: it is a hardware limitation. 360 extra milliseconds after 2,700 seconds is a difference of only 133 ppm (parts per million). The Arduino Nano is clocked off a ceramic resonator, and these time sources carry a typical error of the order of 1,000 ppm. The best thing the code can do is count the clock cycles with perfect accuracy, which makes the software timing as good as the underlying hardware, but never better.</p> <p>Some options you may try:</p> <ol> <li><p>The one that seems most obvious is to have the first Arduino somehow send a trigger signal to the second one when it activates the first relay. Or have the second Arduino sense the state of that relay. Then, all the second Arduino has to do is wait for 360 ms, which it can easily do with reasonable accuracy.</p> </li> <li><p>If there is no way the Arduinos can communicate, then you could try to add external time sources to the Arduinos. Some RTC modules can output a 32,768 Hz signal that could be accurate enough for your needs. Look for a temperature-compensated RTC, as those are more accurate.</p> </li> <li><p>If you cannot add extra hardware, you could try to calibrate the clocks of your Arduinos in order to compensate for their relative drift. Keep in mind though that the drift rate is temperature-dependent, and wanders randomly even at constant temperature. First read the article <a href="http://jorisvr.nl/article/arduino-frequency" rel="nofollow noreferrer">Arduino clock frequency accuracy</a>, by Joris_VR, to get an idea of the accuracy you could expect from such calibration.</p> </li> </ol>
91938
|esp8266|sleep|
Is it possible to know how long an ESP8266 was in deep sleep?
2023-01-12T10:51:46.950
<p>I'm working on a low power device that implements an ESP8266 MCU and uses it's deep sleep feature. The firmware uses the Arduino C++ library.</p> <p>Part of the functionality requires knowing the time. To do this, I am using <code>configTime</code> to get the time (i.e. NTP). But, to reduce power consumption, I only connect to WiFi every 24 hours. The ESP8266 wakes every hour (to decide if it should do something or go back to sleep). To keep time, I record the last known unix timestamp to RTC memory and upon waking add the amount of time that the device was told to deep sleep (i.e. 1 hour).</p> <p>The flaw in this design: Part of the requirement is that the user needs to be able to wake the device manually with a button press and interrupt the normal sleep pattern, but if the device is woken with the reset button, it adds an hour to the time and the time becomes completely inaccurate (because an hour was added, even though it could be seconds since deep sleep started).</p> <p>Is there a way, using the ESP8266 API, to tell how long the device was <em>actually</em> in deep sleep? That way, on wake, instead of blindly adding 1 hour to the RTC-saved unix timestamp, I can add the amount of time that the MCU was in deep sleep. The <a href="https://www.espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf" rel="nofollow noreferrer">datasheet</a> seems to only mention the RTC a few times in not much detail.</p> <p>If no firmware solution exists, what hardware solution could I use?</p> <p>Thinking out loud: I think a compromise could be to detect if the reset button was pressed (latch/flip flop/register, maybe?). In this case I still wouldn't be able to tell how long the MCU was asleep, but at least I'd be able to tell if I should add time. I found that <code>system_get_rst_info</code> is based on how the device went to sleep (i.e. if woken from deep sleep by pressing the reset button, the reason is <code>REANSON_DEEP_SLEEP_AWAKE</code>), so I couldn't see how to make use of that in this case. I suppose I could add an external RTC, negating the need to calculate how long the MCU was in deep sleep, and just use that external IC for time keeping.</p> <p>Edit: Apparently, <a href="https://nodemcu.readthedocs.io/en/release/modules/rtctime/#rtctimedsleep" rel="nofollow noreferrer"><code>rtctime.dsleep()</code></a> provides time keeping across deep sleep, but it's <a href="https://www.esp8266.com/viewtopic.php?p=67168" rel="nofollow noreferrer">LUA only</a> so not useful to me. The <a href="https://github.com/nodemcu/nodemcu-firmware/blob/release/app/modules/rtctime.c" rel="nofollow noreferrer">source</a> is written in C, but I can't see anything that would help.</p> <blockquote> <p>Time is kept across the deep sleep. I.e. rtctime.get() will keep working (provided time was available before the sleep).</p> </blockquote>
<p>I believe the answer is <strong>no</strong> (you cannot tell exactly how long an ESP8266 was asleep), given these constraints:</p> <ol> <li>If an external RTC cannot be used.</li> <li>If the MCU does not connect to Wi-Fi every time it wakes.</li> <li>If the MCU can be woken arbitrarily by the user pressing the reset button.</li> </ol> <p>In other words, if the ESP8266 does not connect to Wi-Fi every time it wakes, you can only estimate the time based on how long it <em>should</em> have been in deep sleep, but you can't know for sure without either going online or using an external RTC.</p>
91944
|arduino-uno|data-type|wire-library|
Wire.write invalid conversion from ‘char*’ to ‘const uint8_t*
2023-01-13T02:14:56.613
<p>I have written this code:</p> <pre><code>char message[4]; memcpy(message, &amp;delta, 4); Wire.write(message, 4); </code></pre> <p>When I try to compile I get this warning:</p> <pre><code>warning: invalid conversion from ‘char*’ to ‘const uint8_t* {aka const unsigned char*}’ [-fpermissive] Wire.write(message, 4); ^ </code></pre> <p>Also followed by this note:</p> <pre><code>In file included from main.ino:5:0: /usr/share/arduino/libraries/Wire/Wire.h:61:20: note: initializing argument 1 of ‘virtual size_t TwoWire::write(const uint8_t*, size_t)’ virtual size_t write(const uint8_t *, size_t); ^ </code></pre> <p>I do not understand what is wrong?</p>
<p>Try</p> <pre><code>Wire.write((const uint8_t*) message, 4); </code></pre> <p>I.e., cast it to the correct type, uint8_t and char are the same (at least on Arduino and for this example, as you do not char about unsigned/signed values).</p> <p>(see also the comment of the busybee below, for using the cleaner C++ cast).</p>
91946
|c|data-type|pointer|
How to send multiple bytes with Wire without copying
2023-01-13T04:03:02.013
<p>When I need to send multiple bytes via Wire, for example a long int, I cast it to a byte array and specify a length</p> <pre><code>long int i; Wire.write((byte*)&amp;i, 4); </code></pre> <p>But if I want to send bytes from more than 1 variable I need to create a buffer</p> <pre><code>byte i; byte j; byte message[2] = {i, j}; Wire.write(message, 2); </code></pre> <p>If I want to send them without copying the data I can put them in a struct</p> <pre><code>struct message { byte i; byte j; }; Wire.write((byte*)&amp;message, 2); </code></pre> <p>But this would require me to refactor existing code.</p> <p>Is there any c voodoo that I can perform to send bytes of different places of my code over Wire without copying them in a buffer and without refactoring the code?</p>
<p>As @chrisl said, there is an internal buffer so the best I can do is just use multiple <code>Wire.write</code> calls, but in my case that wasn't working. I got only the last written value or rubbish data.</p> <p>I dug through the source of the Wire library and found that <a href="https://github.com/arduino/ArduinoCore-avr/blob/8b327d7bede1c1245db99daeba4e168c92c11194/libraries/Wire/src/utility/twi.c#L342" rel="nofollow noreferrer">the version in github</a> (as of this writing) makes it possible to use multiple writes by appending to the buffer:</p> <pre><code>// set length and copy data into tx buffer for(i = 0; i &lt; length; ++i){ twi_txBuffer[twi_txBufferLength+i] = data[i]; } twi_txBufferLength += length; </code></pre> <p>But the one I have installed locally looks like this:</p> <pre><code>// set length and copy data into tx buffer twi_txBufferLength = length; for(i = 0; i &lt; length; ++i){ twi_txBuffer[i] = data[i]; } </code></pre> <p>So that explains a lot.</p> <p>In case someone else also has this problem, you just need to update.</p> <p>I was even too lazy to update, so I just replaced the function. Probably not the best decision, but it works!</p> <p>Thanks!</p>
91950
|serial|softwareserial|
Cannot communicate with software serial on particular devices (SIM7600G-H)
2023-01-13T08:07:04.837
<p>I have 3 devices:</p> <ul> <li>An <a href="https://auseparts.com.au/SainSmart-UNO-ATMEGA328P-PU-ATMEGA8U2-Microcontroller" rel="nofollow noreferrer">UNO</a> (non-genuine)</li> </ul> <p><a href="https://i.stack.imgur.com/4QNLxs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4QNLxs.png" alt="UNO" /></a></p> <ul> <li>An <a href="https://core-electronics.com.au/sim7600g-h-m2-4g-hat-for-raspberry-pi-lte-cat4-high-speed-4g3g2g-gnss-global-band-1.html" rel="nofollow noreferrer">SMS hat/shield device <code>SIM7600G-H</code></a> to communicate with via UART</li> </ul> <p><a href="https://i.stack.imgur.com/A9I7Fs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9I7Fs.png" alt="SMS Device" /></a></p> <ul> <li>A <a href="https://core-electronics.com.au/usb-to-ttl-uart-rs232-serial-converter-module-pl2303hx-au-local-shipping.html" rel="nofollow noreferrer">USB UART controller</a> for debugging purposes</li> </ul> <p><a href="https://i.stack.imgur.com/WIQjYs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WIQjYs.png" alt="UART USB" /></a></p> <hr /> <p>I'm using the UNO to talk to the SMS device via UART at <code>9600</code> baud to send and receive SMS commands. I need the hardware port open to debug, and I am trying to use a software port to talk to the SMS device via it's TX RX pins.</p> <p>But I cannot get the software port to talk to the SMS device at all.</p> <p>This is the success I've had trying to talk to and from devices. The bold boxes are needed to be solved for this setup to work. ✅ = working coms, ❌ = nothing on coms at all. Read left to right, <strong>HAT serial (SMS DEVICE)</strong> can communicate with UNO hardware serial.</p> <p><a href="https://i.stack.imgur.com/ojMCll.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ojMCll.png" alt="Connection matrix" /></a></p> <p>And I'm using this code to just relay inputs and outputs between the hardware and software ports for testing.</p> <pre class="lang-cpp prettyprint-override"><code>// Must be same on mock and serial const int baud = 9600; // Communication with mock hat SoftwareSerial mockPort(2, 3); void setup() { Serial.begin(baud); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } mockPort.begin(baud); Serial.println(&quot;Mock port has started @ &quot; + String(baud)); } void loop() { while (mockPort.available() &gt; 0) { char inByte = mockPort.read(); // and send to the hardware serial port: Serial.write(inByte); } // while there is data coming in FROM SERIAL, read it and send it back to mock while (Serial.available() &gt; 0) { char inByte = Serial.read(); // and send to the mock serial port: mockPort.write(inByte); } } </code></pre> <p>Why can't I communicate to the SMS device with the software ports? (or the USB UART as well?) When testing, I can see the UNO's RX light turn on, but I never receive any data back from the SMS device (the serial monitor is just black).</p> <hr /> <p>Notes:</p> <ul> <li>I've tried the AltSoftSerial library as well</li> <li>I've set the SMS hat's baud rate default to <code>9600</code></li> <li>I've tried different communication pins</li> <li>I've got the TX pins on RX pins and vice versa</li> </ul>
<p>The <code>TX</code> and <code>RX</code> labels mirror the Raspberry Pi. So I swapped the <code>RX</code> and <code>TX</code> wires to connect as <code>RX</code>-&gt;<code>RX</code> and <code>TX</code>-&gt;<code>TX</code> and now it works</p>
91956
|communication|
Can an Arduino and an NI USB-6009 DAQ board interfere with each other's signals when they are simultaneously reading signals from different sensors?
2023-01-13T21:38:53.467
<p>Hello dear Arduino SE community.</p> <p>I have 5 sensors. I read 4 of them with an NI USB-6009 DAQ board and I read the fifth one with an Arduino UNO R3. Though, with the fifth sensor not only I read a signal from it, but I also send a signal to it.</p> <p>Both the Arduino and the NI board are connected to a computer via two different USB ports and send the signals to the computer simultaneously. Also - simultaneously - the Arduino sends a signal to the fifth sensor.</p> <p>I noticed a strange behavior with the signal from one of the sensors read by the NI board. It starts with giving me a signal that is clearly wrong and over the course of, approximately, 5 minutes gradually changes to a correct reading.</p> <p>That hadn't happened when I didn't have Arduino connected to the computer at the same time.</p> <p>Thus, I'm wondering if it is possible that an Arduino and an NI board can interfere with each other's signals when connected to the computer simultaneously. If it is possible, is it something widespread and is there a working solution?</p> <p>Thank you in advance. Ivan</p> <p>P.S. I deliberately don't provide the specs of my system because the point of my question is not to resolve the issue but to learn if what I described is possible theoretically and if such cases have been encountered.</p>
<p>I have found a solution to my problem.</p> <p>The sensor that was giving me the wrong signal was plugged to the same electrical circuit with &quot;heavy&quot; equipment (two DC laboratory power supplies). It is well known that one shouldn't do it because &quot;heavy&quot; equipment sends noise back to the circuit which, ultimately, causes noise in the signal generated by the sensor.</p> <p>Thus, my issue had nothing to do with the Arduino interfering with the USB-6009 through the computer.</p> <p>To make sure, I disconnected the Arduino from the computer and still got the same wrong signal from the problematic sensor. Then, I plugged the problematic sensor to another electrical circuit, connected the Arduino back to the computer and got the right signal.</p> <p>Thus, I conclude that one can safely use an Arduino and a USB-6009 with the same computer.</p>
91960
|digital|speed|digitalwrite|
How to increase pinout switching?
2023-01-14T12:09:21.317
<p>Consider this code:</p> <pre><code>void loop() { digitalWrite(pinTest, HIGH); digitalWrite(pinTest, LOW); } </code></pre> <p>On an Arduino Mega 2560, running 16MHz (=0.06us), I would expect the width of the pulse to be somewhere around 0.1us.</p> <p>However, when measuring with my oscilloscope, I get around 4us high and 5-6 us low. I understand it could take some cycles to run the <code>digitalWrite</code> code, but this seems quite a lot.</p> <p>How is that difference explained?</p>
<p>You do not need to go all the way down to assembly in order to get that speed. You can do direct port access from your <code>.ino</code> file:</p> <pre class="lang-cpp prettyprint-override"><code>void setup() { DDRA |= _BV(PA0); // pin 22 = PA0 as output for (;;) { PINA |= _BV(PA0); // toggle PA0 } } void loop(){} </code></pre> <p>This compiles to something that is almost equivalent to your assembly code. Actually, it is a bit faster, as it uses <code>rjmp</code> instead of the slower <code>jmp</code> instruction.</p> <p><strong>Edit</strong>: A few notes</p> <ol> <li><p>As pointed out by timemage in a comment, you can save another CPU cycle by writing <code>PINA =</code> instead of <code>PINA |=</code>.</p> </li> <li><p>This code, as well as your two examples, will exhibit a glitch every 1,024 µs. This is caused by the periodic timer interrupt used by the Arduino core for timekeeping (<code>millis()</code>, <code>micros()</code> and <code>delay()</code>). You can avoid the glitch by disabling interrupts before going into the tight loop. Alternatively, if you do not use the Arduino core at all, you can define a function called <code>main()</code> instead of <code>setup()</code> and <code>loop()</code>: this will completely remove the Arduino core initialization for your compiled program.</p> </li> <li><p><code>arduino-cli</code> is useful for sparing you the complexity of the Arduino build system (automatic installation of the cores and libraries, libraries in multiple places that depend on the core you use...). If you do not use the Arduino core, <code>arduino-cli</code> is of little use: a very simple Makefile that calls <code>avr-gcc</code> and <code>avrdude</code> is all you need for basic AVR development.</p> </li> </ol>
91983
|ide|error|arduino-ide-2|
Arduino Output Panel Font Color Change
2023-01-16T17:02:08.333
<p>I am using Arduino IDE 2.0.3. When compiling code if there is an error it shows on a black background with a red font, that is hard for me to read. Can I change either the background or the font? Looking within the IDE I don't see how and not seeing anything on the internet. TIA</p>
<p>Thank you dankeboy36 for pointing out &quot;Themes&quot;. Fixed it right up.</p>
91995
|programming|c++|
How does Arduino handle passing this union?
2023-01-17T21:56:42.543
<p>I'm unsure how this will be handled by the Arduino compiler. If anyone can explain what and why, I'd appreciate it. This is obviously very simplified, but it does contain the actual issue.</p> <p>At the module level I have this <code>union</code>. I understand that this is strictly speaking not correct C++, but it does work for me, at least when used directly and not passed as a argument to a function.</p> <pre><code> union _TAT { // access as bytes or uint32 uint32_t wide = 0; uint8_t bytes[4]; }; _TAT oneTAT; // a variable of _TAT </code></pre> <p>Suppose I also have a function that works on these:</p> <pre><code> void fix_Term(_TAT atat) { atat.wide = 0; atat.bytes[3] = 17; } </code></pre> <p>...and I invoke it with:</p> <pre><code> fix_Term(oneTAT); </code></pre> <p>As I understand it, passing <code>AnArray[]</code> is equivalent to passing <code>*AnArray</code>, so the function might/should see <code>atat.bytes[3]</code> as a pointer to that byte of the variable. But what about <code>atat.wide</code>? I haven't explicitly passed <code>oneTAT</code> by reference, so...?</p> <p>What might actually happen here? It does compile without complaint but I can't test it because the hardware it depends on isn't available yet. Besides, even if it works, I'd like to know why.</p> <p>And of course, if it's just wrong, how do I best accomplish passing and modifying a variable like this?</p>
<p>It is confusing in C and C++ that arrays are passed as pointers but an instance of class, struct or union is always passed by value (so as a copy) including the arrays which are part of the memory space of the structure as in the case of your union.</p> <p>If you want to pass by reference, declare the function's parameter as a reference 'type'. For example <code>void fix_Term(_TAT&amp; atat) {</code>.</p>
92000
|arduino-nano|multiplexer|
Multiplexing three VFD tubes — why are the segments and the display timing incorrect?
2023-01-18T10:36:46.993
<p>I'm using an Arduino Nano, a UNL2803 IC, and three 2N3904 transistors to drive three seven-segment vacuum fluorescent display tubes (IV-6) in a multiplex configuration. The UNL2803 is used to drive the segments: when an Arduino pin is pulled low, 25V is sent to the corresponding segment. The 2N3904 transistors are used to drive each of the digits: when the Arduino pin is high, 25V is sent to the digit's grid, thereby activating the digit.</p> <p>The problem: the tubes aren't showing the correct segments, and the displays aren't being activated with correct timing. I have checked each segment connection to make sure it is connected to the correct segment. By slowing down the time interval between digits, I can see that the second and third digits (the 10s and 1s) are being displayed sequentially with the correct interval, but the first digit (the 100s) comes on with the second digit and stays on for twice the interval time. It also appears that some of the digits are attempting to display more than one number (sequentially) while activated.</p> <p>The code:</p> <pre><code>// Pin assignments for segments const int SEG_A = 2; const int SEG_B = 3; const int SEG_C = 4; const int SEG_D = 6; const int SEG_E = 5; const int SEG_F = 7; const int SEG_G = 8; // Pin assignments for digits const int DIG1 = 9; const int DIG2 = 10; const int DIG3 = 11; int digit = 1; int dig_number = 0; unsigned int number = 321; void setup() { Serial.begin(9600); // Set segment pins as outputs pinMode(SEG_A, OUTPUT); pinMode(SEG_B, OUTPUT); pinMode(SEG_C, OUTPUT); pinMode(SEG_D, OUTPUT); pinMode(SEG_E, OUTPUT); pinMode(SEG_F, OUTPUT); pinMode(SEG_G, OUTPUT); // Set digit pins as outputs pinMode(DIG1, OUTPUT); pinMode(DIG2, OUTPUT); pinMode(DIG3, OUTPUT); // Turn off digits digitalWrite(DIG1, LOW); digitalWrite(DIG2, LOW); digitalWrite(DIG3, LOW); } void loop() { if (digit == 1) { digitalWrite(DIG1, HIGH); digitalWrite(DIG2, LOW); digitalWrite(DIG3, LOW); dig_number = number / 100; if (number &lt; 100) { // to disable the digit if it's not being used dig_number == 99; // triggers 'default' in switch/case display_number(dig_number); } else { display_number(dig_number); } digit = 2; Serial.println(&quot;The first digit is: &quot;); Serial.print(dig_number); delay (250); } if (digit == 2) { digitalWrite(DIG1, LOW); digitalWrite(DIG2, HIGH); digitalWrite(DIG3, LOW); dig_number = (number / 10) % 10; if (dig_number == 0 &amp;&amp; number &lt; 10) { // to disable the digit if it's not being used dig_number == 99; // triggers 'default' in switch/case display_number(dig_number); } else { display_number(dig_number); } digit = 3; Serial.println(&quot;The second digit is: &quot;); Serial.print(dig_number); delay (250); } if (digit == 3) { digitalWrite(DIG1, LOW); digitalWrite(DIG2, LOW); digitalWrite(DIG3, HIGH); dig_number = number % 10; display_number(dig_number); digit = 1; Serial.println(&quot;The third digit is: &quot;); Serial.print(dig_number); delay (250); } } void display_number(int dig_number) { switch (dig_number) { case 0: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, LOW); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, HIGH); break; case 1: digitalWrite(SEG_A, HIGH); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, HIGH); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, HIGH); digitalWrite(SEG_G, HIGH); break; case 2: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, HIGH); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, LOW); digitalWrite(SEG_F, HIGH); digitalWrite(SEG_G, LOW); break; case 3: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, HIGH); digitalWrite(SEG_G, LOW); break; case 4: digitalWrite(SEG_A, HIGH); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, HIGH); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, LOW); break; case 5: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, HIGH); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, LOW); break; case 6: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, HIGH); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, LOW); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, LOW); break; case 7: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, HIGH); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, HIGH); digitalWrite(SEG_G, HIGH); break; case 8: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, LOW); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, LOW); break; case 9: digitalWrite(SEG_A, LOW); digitalWrite(SEG_B, LOW); digitalWrite(SEG_C, LOW); digitalWrite(SEG_D, LOW); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, LOW); digitalWrite(SEG_G, LOW); break; default: digitalWrite(SEG_A, HIGH); digitalWrite(SEG_B, HIGH); digitalWrite(SEG_C, HIGH); digitalWrite(SEG_D, HIGH); digitalWrite(SEG_E, HIGH); digitalWrite(SEG_F, HIGH); digitalWrite(SEG_G, HIGH); break; } } </code></pre> <p>The circuit diagram:</p> <p><a href="https://i.stack.imgur.com/8OIcP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8OIcP.png" alt="enter image description here" /></a></p> <p>I have heard rumor that using delay() instead of millis() for multiplexing can be problematic. Is that what's going on here?</p> <p>Many thanks in advance for considering this problem!</p>
<p>For future searchers, I finally got this circuit going using two ULN2803 transistor arrays, instead of discrete transistors for the digit connections. Here's the final schematic:</p> <p><a href="https://i.stack.imgur.com/F2YWv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F2YWv.png" alt="enter image description here" /></a></p> <p>You can check out more about the final project <a href="https://www.hackster.io/tmburns/driving-vfd-tubes-with-an-arduino-nano-14f71e" rel="nofollow noreferrer">here</a>. Many thanks to those who commented——your feedback was very helpful!</p>
92010
|serial|usb|ethernet-shield|
Can an ethernet shield function as an adapter?
2023-01-19T03:14:54.267
<p>I want to communicate with my Arduino over a long distance so I decided to use an Ethernet cable between my computer and Arduino. Searching up a few tutorials I've found them all mentioning IP addresses and establishing a network.</p> <p>Simply put my question is can an Ethernet shield make the Arduino function basically the same as with a direct USB connection into its port(with Serial and all) without having to establish a network/other things. If so, is it as simple as saying something like &quot;Ethernet.begin()&quot; and then continuing?</p> <p>Thank you, and please note that I (clearly) do not have much TCP/IP experience (but am more than willing to learn).</p>
<p>No, you cannot do that. Ethernet is <em>very</em> different from a serial link. You will have to deal with IP addresses, port numbers, the notions of client and server, and so on. Note that, once you manage to establish a TCP connection through Ethernet, <em>that connection</em> does behave pretty much like a (somewhat virtualized) serial link. But you have to establish the connection first. So you will have to study a bit, read documentations, etc.</p> <p>Alternatively, if you only need a short-distance link (say, a couple of km), you can try RS-485 instead of Ethernet. RS-485 is a physical layer commonly used to transmit regular serial data. From the software point of view, it is pretty much a regular serial link, save for the fact that you usually cannot speak and listen at the same time (you could, with more expensive cabling).</p>
92031
|attiny|
Why are ATTiny so expensive compared to ESP modules compared to features they offer?
2023-01-21T06:27:48.693
<p>I was looking for a cheap MCU solution for a project, apart from being compact, ATTiny doesn't seem to provide much value. I was hoping it is cheaper but nope, They are mostly above 1.5 USD in any shop. Whereas I can easily get an ESP module for a comparable price if not cheaper, added WiFi, and optionally Bluetooth, and they are not too huge for my use cases. Am I missing something?</p>
<p>You can get ATTINYs for much less than $1.50.</p> <p>For example, right now you can order the ATTINY202 from stock in single unit quantiles from Microchip for $0.48 each. They drop to $0.35 each at 5K units (also in stock).</p> <p><a href="https://www.microchipdirect.com/product/search/all/ATTINY202" rel="nofollow noreferrer">https://www.microchipdirect.com/product/search/all/ATTINY202</a></p> <p>If you are really price sensitive then you can sometimes get the smaller ATTINYs for even less when buying in reels at a time, but you have to shop around.</p> <p>Anytime you pick a part you have to trade-off purchase price, availability (both now and in the future), and suitability. The AVR parts can often be the best choice- but all depends on what you are using it for!</p>
92034
|esp8266|core-libraries|
ESP8266 - error after board update to 3.1.1
2023-01-21T09:40:29.807
<p>I'm using a Ubuntu 22.04 and Arduino IDE 1.8.19 for my ESP8266 Projects.</p> <p>Yesterday I upgraded to 3.1.1 (using board library manager), and right after that - I got the following message (few seconds after compilation start):</p> <pre><code>Traceback (most recent call last): File &quot;/home/guy/snap/arduino/85/.arduino15/packages/esp8266/hardware/esp8266/3.1.1/tools/mkbuildoptglobals.py&quot;, line 846, in &lt;module&gt; sys.exit(main()) File &quot;/home/guy/snap/arduino/85/.arduino15/packages/esp8266/hardware/esp8266/3.1.1/tools/mkbuildoptglobals.py&quot;, line 759, in main if time.time_ns() &lt; os.stat(commonhfile_fqfn).st_mtime_ns: AttributeError: module 'time' has no attribute 'time_ns' exit status 1 Error compiling for board LOLIN(WEMOS) D1 R2 &amp; mini. </code></pre> <p>Steps done to find the reason:</p> <ol> <li>Empty Sketch - occurs.</li> <li>Any other ESP8266 board - occurs.</li> <li>Going back to prior version, 3.1.0 - occurs.</li> <li>Going back to 3.0.2 - OK!</li> <li>Checking 3.1.1 on Mac, same IDE version - OK!</li> </ol> <p>Any ideas why ? Am I the only one ?</p> <p>Guy</p>
<p>The error tells you, that the time.time_ns() python function does not exist. This function was added to the python time lib with Python3 version 3.7.</p> <p>The most likely scenario I can imagin here is, that a python 3.6 or lower version is installed on your ubuntu and therefore the board software does not find the required function.</p> <p>Depending on how the ARDUINO IDE is configured, the globally installed python or a special installation of python is used. We dicussed these two possibilities in the chat and realized that in your case, snap installs its own dependency of python. I assume that the version of this python was below 3.7 and therefore the plugin was unable to find the required time function.</p> <p>If the Arduino IDe would have been depent on the global python installation, it would have been enough to install a newer python (e.g. 3.10+) globally.</p> <p>In you case (dependency defined by snap), the only solution I have, is to install the IDE not with snap but with the manual installation or by using apt. There are instruction in the internet like <a href="https://www.computingpost.com/how-to-install-arduino-ide-on-ubuntu-22-04-lts/" rel="nofollow noreferrer">https://www.computingpost.com/how-to-install-arduino-ide-on-ubuntu-22-04-lts/</a>.</p> <p>Please check the comment of @userfuser (about usíng an .AppImage file) in the dicussion below the question also.</p>
92059
|class|isr|
How do I properly use an ISR inside a class definition?
2023-01-23T18:41:58.257
<p>I want to write a class for a model bike.</p> <p>For controlling the steering I use a DC motor with two encoders. To get the steering angle <code>stAng</code> of the bike, I attach a interrupt to the pin <code>ST_ENC_A</code> where one of the encoders is connected to. This interrupt is attached when the bike is initialized with the function <code>bike.begin()</code>. When the interrupt is triggerd, the increment-steering-angle-function <code>incStAng</code> is triggerd. Said function is member of the class <code>Bike</code>. To make the whole code compile and upload I had to make the increment-steering-angle-function <code>static void incStAng()</code> and the steering-angle-variable <code>volatile static float stAng</code> static.</p> <p>The code is running, there are no errors or warnings.</p> <p>Now, when I provide pin <code>ST_ENC_A</code> with 3.3V the interrupt should be triggerd and I should see the printed value of <code>stAng</code> increse in the Serial Monitor. This is not the case. It stays at 0.00.</p> <p>This is my first real class I am writing. I only want to create one instance of my bike so the static definition of <code>stAng</code> and <code>incStAng</code> should be no problem.</p> <p>So far I found the following websites helpful for information on '<a href="https://stackoverflow.com/questions/31305717/member-function-with-static-linkage">static</a>' and <a href="https://forum.arduino.cc/t/using-a-class-member-for-isr-is-it-possible/380127" rel="nofollow noreferrer">ISR</a>.</p> <p>I would be glad if someone could help me and give me a hint why the steering angle is not increasing when I give said pin 3.3V!</p> <p>Board: Arduino Nano RP2040 Connect</p> <p>Below you will see the .ino, .h, .cpp files in this order.</p> <pre><code>// myBike.ino - main file #include &quot;Bike.h&quot; Bike bike; void setup() { Serial.begin(9600); bike.begin(); } void loop() { float val = bike.getStAng(); Serial.println(val); } </code></pre> <pre><code>// Bike.h - header file for the Bike library #ifndef Bike_h #define Bike_h #include &quot;Arduino.h&quot; class Bike { public: Bike(); void begin(); float getStAng(); private: volatile static float stAng; static void incStAng(); }; #endif </code></pre> <pre><code>// Bike.cpp - implementation file for the Bike library #include &quot;Bike.h&quot; #define ST_ENC_A 12 #define ST_ENC_B 11 #define DEG_PER_CNT 0.51428571428 Bike::Bike() { pinMode(ST_ENC_A, INPUT); pinMode(ST_ENC_B, INPUT); } void Bike::begin() { attachInterrupt(digitalPinToInterrupt(ST_ENC_A),incStAng,RISING); } void Bike::incStAng() { volatile float stAng; int b = digitalRead(ST_ENC_B); if(b==HIGH){ stAng = stAng - DEG_PER_CNT; }else{ stAng = stAng - DEG_PER_CNT; } } float Bike::getStAng() { volatile float stAng; return stAng; } </code></pre>
<p>You have <em>three</em> different variables named <code>stAng</code> here:</p> <ul> <li>a static member of the <code>Bike</code> class, which has been declared but not defined, and is never used</li> <li>a local variable of the <code>Bike::incStAng()</code> method</li> <li>a local variable of the <code>Bike::getStAng()</code> method</li> </ul> <p>There should be only one such variable. For this, you should define the first one: in Bike.cpp</p> <pre class="lang-cpp prettyprint-override"><code>volatile float Bike::stAng; </code></pre> <p>and get rid of the other two.</p> <p>Side note: I would recommend avoiding floating point computations within an ISR, as these can be quite slow. Instead, count the <em>integer</em> number of encoder steps in the ISR, and convert to an angle within <code>Bike::getStAng()</code>.</p>
92062
|c++|
Passing function as argument, with capture, what type to declare in function?
2023-01-24T04:42:34.103
<p>This probably has a simple resolution, but can't find the right combination.</p> <p>I'm trying to setup a function (<code>setupScreen</code>) to take as an argument a function to do the actual setup:</p> <pre class="lang-cpp prettyprint-override"><code>void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){ ScreenHelpers::waitTilCanRefreshScreen(); (* setupFunc)(&amp;display_two); lastUpdateTime = millis(); } //... void ScreenHelpers::displayErrorMessage(const String message){ const char* text = message.c_str(); ScreenHelpers::setupScreen([text](ThinkInk_290_Tricolor_Z10* screen) { screen-&gt;clearBuffer(); ScreenHelpers::simpleDisplayText( screen, text, EPD_RED ); }); } </code></pre> <p>This works, until I added the <code>[text]</code> to capture the <code>text</code> variable in the lambda, where it resulted in:</p> <pre><code>ScreenHelpers.cpp: In static member function 'static void ScreenHelpers::displayErrorMessage(String)': ScreenHelpers.cpp:45:4: error: no matching function for call to 'ScreenHelpers::setupScreen(ScreenHelpers::displayErrorMessage(String)::&lt;lambda(ThinkInk_290_Tricolor_Z10*)&gt;)' }); ^ ScreenHelpers.cpp:21:6: note: candidate: 'static void ScreenHelpers::setupScreen(void (*)(ThinkInk_290_Tricolor_Z10*))' void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){ ^~~~~~~~~~~~~ </code></pre> <p>What should my function declaration look like to accept this?</p>
<p><code>ScreenHelpers::setupScreen()</code> expects its argument to be a plain function. A capturing lambda is not a plain function: it is rather a functor, i.e. an object that is callable like a function.</p> <p>The standard way of passing such a lambda in C++ is to declare the parameter to be of type <a href="https://en.cppreference.com/w/cpp/utility/functional/function" rel="nofollow noreferrer"><code>std::function</code></a>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;functional&gt; void ScreenHelpers::setupScreen(std::function&lt;void(ThinkInk_290_Tricolor_Z10*)&gt; setupFunc) { ... } </code></pre> <p>This may or may not work depending on the Arduino board you are using. AVR-based boards rely on a C library that only minimally supports C++. You cannot use <code>&lt;functional&gt;</code> on those boards. If you are using one of those boards, your options are:</p> <ol> <li><p>Try to find an implementation of of the C++ STL for AVR-based boards. I have seen at least one floating around in the Net.</p> </li> <li><p>Use the standard C idiom for defining a callback with a <code>void*</code> parameter:</p> </li> </ol> <pre class="lang-cpp prettyprint-override"><code>void ScreenHelpers::setupScreen( void (*setupFunc)(ThinkInk_290_Tricolor_Z10*, void*), void *callback_data) { setupFunc(&amp;display_two, callback_data); //... } // elsewhere: ScreenHelpers::setupScreen([](ThinkInk_290_Tricolor_Z10 *screen, void *data) { const char *text = (const char *) data; // ... }, (void *) text); </code></pre>
92074
|esp32|
Can I power Lilygo TTGo T-display from 5v and still use USB for communication?
2023-01-25T17:22:36.613
<p>I have a project which needs a 7-9V power source. I use a battery, and plan to use a small regulator to supply 5V to a Lilygo TTGO T-Display V1.1 (1.14 inch display) via the 5V and GND pins.</p> <p>I need to connect the Lilygo to USB from time-to-time to upload data. <em>Will there be any conflict between the USB power and the 5V supply ?</em></p> <p>I have peered for a long time at the schematic, and I see that there are MOSFETs doing some kind of protection, but I do not understand it well enough to be sure. <strong>Schematic</strong>: <a href="https://raw.githubusercontent.com/Xinyuan-LilyGO/TTGO-T-Display/master/schematic/ESP32-TFT(6-26).pdf" rel="nofollow noreferrer">here</a></p> <ol> <li>Q5 appears to disconnect the battery (VBAT) from +5V when the USB is connected.</li> <li>Q4 also seems to disconnect the battery (BAT) from +5V when the USB is connected. <em>What is the difference between VBAT and BAT ?</em></li> <li>VBUS (the USB power) is connected to +5V via a Zener diode. This appears to allow the USB to supply 5V, but prevent current flowing back to the PC. I think there could be an issue with high current through the Zener if my 5V regulator gave a voltage that was lower than the USB.</li> </ol>
<p>What are you trying to achieve? For how long is the board supposed to function? The simplest solution in this case is to simply get a 4.2V battery for the LilyGO board itself, most likely not just in terms of effort, but economically.</p> <p>From your edits, I (now) assume you want to use the 5V pin on the board? I don't think that'll work the way you'd want it to, as it doesn't seem that it was intended for that (if it was, the VIN pin would've been brought out).</p> <ol> <li> <blockquote> <p>Q5 appears to disconnect the battery (VBAT) from +5V when the USB is connected.</p> </blockquote> </li> </ol> <p>Yeah, that makes sense to me as well.</p> <ol start="2"> <li> <blockquote> <p>Q4 also seems to disconnect the battery (BAT) from +5V when the USB is connected. What is the difference between VBAT and BAT ?</p> </blockquote> </li> </ol> <p>Yes, looking at the datasheet for the battery charger and the schematic for the LilyGO board, VBAT is the batteries voltage, while the BAT terminal is the one coming out of the charger and the one that usually supplies the current to both charge the battery and to possibly drive the system load.</p> <ol start="3"> <li> <blockquote> <p>VBUS (the USB power) is connected to +5V via a Zener diode. This appears to allow the USB to supply 5V, but prevent current flowing back to the PC. I think there could be an issue with high current through the Zener if my 5V regulator gave a voltage that was lower than the USB.</p> </blockquote> </li> </ol> <p>Yeah, it prevents the current going back into the USB port if you have the battery connected. You need a pretty substantial voltage to overcome that Schottky* barrier.</p> <p>One issue you'll probably encounter is that if you connect a 5V source to that pin, the system will think it's powered on by a battery and you can damage the BAT terminal. If you have more than 1 of those boards and you're willing to experiment, you could try cutting the trace to BAT terminal altogether and connecting the 5V source and seeing if that works.</p> <p>Another issue is that for safety reasons, it'd be prudent to switch that source off when you're connecting the USB; you'd also want to protect that 5V source from being damaged by the VUSB once it's on. There are probably ways you could keep the 5V on if you desolder the USBC connector and try to manually attach a probe to the datalines and ground the two together, but dealing with USBC is not easy and you're rapidly venturing into territory where it's just easier to get a different board and the screen separately or just use a LiPo battery to power the board in the first place (you could probably find a way to use multiple LiPo packs if you need your application to last longer as well).</p> <p>Note: I didn't spend too much time looking at the schematic and it is a bit confusing, so a possible good exercise would be to simulate those two circuits in a SPICE program. And again, these types of questions are covered more-so by the EE SE. If you'd have posted it there, I'm sure you'd get more (and most likely, better) answers.</p>
92078
|serial|communication|timing|
Arduino Timer Drift Issue
2023-01-26T03:03:04.593
<p>I have two Arduinos that communicate over serial. Each arduino runs a TDMA algorithm where each arduino is assigned one timeslot. The arduinos should transmit during their timeslot, which does work fine. However, over time, say 10-15 minutes the arduinos start to overlap their timeslots. To keep time I am using the millis() function to determine when to send a message. I have tried both delay() and manually setting up counters but getting the same drifting behavior. On one of the iterations of the code I had a Serial.readStringUntil() function that was being called during every timeslot and the arduinos stayed in sync for over 13 hours with no detected drift, with an exact timeslot of 1000ms. I now am aware that the delay I was seeing is caused by the timeout parameter, which defaults to 1000ms, in the readStringUntil function, but it does not make sense that there would be no drift when the arduino was delayed in this way. I know that the stability of the ceramic resonator on each arduino would cause drift.</p> <p>Why would delay(), millis(), and manually configuring timer1 cause drift, but the timeout functionality of the readStringUntil function seemingly does not drift?</p> <p>Also, is there a better way to setup the timing functionality, the goal is to have the nodes go as long as possible without needing a resync?</p> <p>The following psuedo is how the timing is currently setup.</p> <pre><code>count = 0; if(millis() - previous_action &gt;= TIME_SLOT) { count++; if(correct timeslot) { TRANSMIT(); } previous_action = millis(); loop_back_to_check; } </code></pre> <p>EDIT: RTC and other devices that can keep the devices sync'd are not in the scope of the project.</p>
<p>According to my experience, they are the clients that should follow the server's timing. On the client side:</p> <ol> <li>On each server transmission, calculate the ETA (Estimated Time of Arrival and ATA (Actual Time of Arrival) of the message, based on your time slot scheduling and adjust your local clock accordingly.</li> <li>It would be nice to treat all transmissions as timing messages, no matter the destination, just ignore the payload.</li> <li>It is obvious that the client should be a little overhead timed, in case the server's clock is a little faster.</li> <li>For long inactive periods, the server should broadcast a periodic timing message, so that the error will be kept to a minimum.</li> <li>It would be convenient to add a &quot;timing preamble&quot; in each transmission.</li> </ol> <p>With all that in mind, the readStringUntil function is your friend in many ways. By waiting for the timing preamble, you can determine easily the timing error. By waiting for a known postamble, you read &quot;late&quot; messages (don't forget the timeout value!).</p> <p>Use a bi-numbering scheme for each transmission, one for each client's message and one for each broadcast (total transmissions). Calculate the minimum convenient modulo (overflow) values. Each client will know if there's something missing. (usually, a too-early transmission or a collision)</p> <p>Although it is communications-medium agile, I would recommend a preamble like:</p> <pre><code>$FF $00 $FF $00 AA BB CC DD EE $FF $FF FF with PAYLOAD following, where: AA = 1 byte, the destination addr, $00 = Broadcast BB = 1 byte, message type (optional, $00 for timing msg) CC = 1..2 bytes, msg no. to this dest. DD = 1..2 (3?) bytes, total msg no., no matter the dest. EE = 1 byte, payload length, if variable. (EE&lt;$FF, $00 for timing msg) FF = 1 byte checksum (optional). (Why should you place it AFTER the &quot;$FF $FF&quot; combination?) </code></pre> <p>Use the time you receive the &quot;$FF $FF&quot; combination as a time-mark to calculate ATA &amp; ETA. (It is common sense to treat your values so that this combination cannot show before the end of the preamble)</p> <p>Consider using a postamble, with redundant info &amp; End-Of-Message mark.</p>
92104
|led|
I don't understand what's wrong with this code
2023-01-29T17:42:50.853
<pre><code>int ledy = 5 ; int leds = 4 ; int ledk = 3; int button = 2 ; int count = 0 ; void setup() { pinMode(ledy, OUTPUT); pinMode(leds, OUTPUT); pinMode(ledk, OUTPUT); pinMode(button,INPUT); randomSeed(analogRead(A0)); } void loop() { if(digitalRead(button)== HIGH) { count = count++ ; } if (count==1) { digitalWrite(ledk, HIGH); digitalWrite(leds, LOW); digitalWrite(ledy, LOW); } else if (count==2) { digitalWrite(ledk, LOW); digitalWrite(leds, HIGH); digitalWrite(ledy, LOW); } else if (count==3) { digitalWrite(ledk, LOW); digitalWrite(leds, LOW); digitalWrite(ledy, HIGH); } delay(1000); } </code></pre> <p>I don't undertstand why it isn't working. I want it three leds to light up one by one as loop. But none of them lights up.</p>
<p>One thing that jumps out to me as a possible cause of your issue here is that many push buttons require a <a href="https://docs.arduino.cc/learn/microcontrollers/digital-pins#properties-of-pins-configured-as-input_pullup" rel="nofollow noreferrer">pull-up resistor</a>, which is provided as an internal component of most microcontrollers, but needs to be specifically requested in the <code>pinMode</code> instantiation of the button. Try changing your <code>setup()</code> function to the following:</p> <pre><code>void setup() { pinMode(ledy, OUTPUT); pinMode(leds, OUTPUT); pinMode(ledk, OUTPUT); pinMode(button,INPUT_PULLUP); randomSeed(analogRead(A0)); } </code></pre> <p>however if you do this, you must also change your if statement to <code>if(digitalRead(button) == LOW)</code>, as a pullup resistor will make it so that when the button is not pressed, the pin is pulled high, and vice-versa.</p> <p>Another way to troubleshoot this is to see if the LEDs light up when you remove the reliance on the button altogether by removing the</p> <pre><code>if(digitalRead(button)== HIGH) { count = count++ ; } </code></pre> <p>and changing it to</p> <pre><code>count++; delay(1000); </code></pre> <p>and see if the LED changes every 1 second (delay requires a millisecond value). I agree with @StarCat that <code>count = count++;</code> possibly isn't doing what you think it is.</p>
92110
|c++|class|stream|
How to pass Strem object to my class
2023-01-30T08:35:24.867
<p>I'm trying to creaper class wraper to use an <code>Stream</code>object but I've an error when I try to compile. My <code>.h</code>file :</p> <pre><code>#include &lt;Arduino.h&gt; class TestSerialListener { public: TestSerialListener(Stream &amp;serial); void testPrint(void); private: bool _listener_start; Stream &amp;_serial; void startListener(void); }; </code></pre> <p>my <code>cpp</code>file</p> <pre><code>#include &quot;TestSerialListener.h&quot; #include &lt;Arduino.h&gt; TestSerialListener::TestSerialListener(Stream &amp;serial) : _serial(serial) { } void TestSerialListener::testPrint(){ _serial.begin(115200); &lt;---------- error compilation _serial.println(&quot;test&quot;); } void TestSerialListener::startListener(void) { if(!_listener_start){ _listener_start = true; } } </code></pre> <p>And when i try to compile it I got this error : <code>error: 'class Stream' has no member named 'begin'</code>Why I can't use <code>begin()</code>in my classe ?</p>
<p>the <code>begin()</code> method is defined in the <code>HardwareSerial</code> class, not in <code>Stream</code>. You can look that up yourself in your Arduino installation. For me these files are placed under <code>~/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/</code> and are named <code>Stream.h</code> and <code>HardwareSerial.h</code>.</p> <p>And if you think about it, this is quite logical. The <code>Stream</code> class can represent any object, that can stream data. It doesn't know anything about how exactly the data is streamed on a hardware level. It just provides the convenient functions for handling the data. The <code>HardwareSerial</code> class then derives from <code>Stream</code> to get those data handling methods and adds its own methods to handle the hardware side of the problem, including setting a baudrate.</p> <p>When providing a <code>Stream</code> reference to a class constructor you want to <code>begin()</code> the corresponding object outside of the class, before you start to stream any data through it. Doing it this way makes your class widely usable, since you could use any <code>Stream</code> object, even a file on an SD card.</p> <p>So move the <code>begin()</code> line from your class to the <code>setup()</code> function in your main code.</p> <hr /> <p>For reference: Juraj showed the inheritance between the classes in his answer to <a href="https://arduino.stackexchange.com/questions/78719/can-you-use-serial-port-as-a-variable/78725#78725">this question</a>. Have a look at it, since it is quite enlightening.</p>
92112
|battery|arduino-pro-mini|
Arduino 3.3v pro mini, most efficient use of AA batteries for power
2023-01-30T13:49:18.507
<p>I want to use a 3.3V pro mini that uses a BME 280 to take temp/pressure/humidity, and nRF24L01 module to transmit the data, at ?10 minute intervals. I want to use 1, 2,3 or 4 AA batteries to power it. I've read all about the techniques to reduce power consumption, by removing the power LED and using sleep functions. But I would like to know the most efficient combination of batteries to use. If I can get a year out of 1 battery and a step-up converter, I would be happiest with that. But perhaps 3 duracell or 4 (rechargeable) batteries connected directly to the Vcc pin (ie no regulator) might be better. Does anyone have first-hand experience to know what works best?</p>
<p>You can definitely do better with another regulator that the on-board ones, which are not energy efficient because they drop the supply voltage through a resistance, wasting the excess current as heat. An external boost regulator would waste much less current (charge, really, since we're trying to make maximum use of the battery capacity, or equivalently, trying to minimize the capacity &amp; space needed to run your system for a year).</p> <p>So you need two things:</p> <ol> <li>The most space-efficient way (I assume...) to store a year's energy needs; and</li> <li>A pretty good idea of what the energy requirement will be.</li> </ol> <p>For (2.), you'll need an energy budget for your system:</p> <ol> <li>How much current your system draws when it is awake;</li> <li>How much current your system draws when it is asleep;</li> <li>It's duty cycle (e.g.: 3% awake time, 97% sleep time), and use that to calculate the total charge in milliAmp-hours the system draws during the 1 year.</li> </ol> <p>Don't forget to account for the batteries' inefficiency when they're cold, if that will be an issue, and add in a safety factor so it won't die before you arrive a year hence to change the batteries.</p> <p>You'll need to consider powering down the sensor(s) and radio(s) during CPU sleep; their idle draw would make sleeping the CPU ineffective (as far as saving battery is concerned).</p> <p>Once you have an energy budget, you can look at the available ways to store and deliver a year's worth - regulator type, size and efficiency; battery size and count) to see what combination will meet your needs for cost, simplicity, and space limitations.</p>
92118
|avrdude|command-line|
What is the difference between ":i" and ":a" in avrdude command?
2023-01-30T19:50:30.863
<p>What is the difference between <code>:i</code> and <code>:a</code> after my hex file path in avrdude command.</p> <pre><code>avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM8 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:i </code></pre> <p>and</p> <pre><code>avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a </code></pre>
<p>These are Avrdude file format specifiers.</p> <pre><code>avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a </code></pre> <p>The final <code>:a</code> in this case is a format specifier meaning &quot;auto detect; valid for input only, and only if the input is not provided at stdin.&quot;</p> <p>An <code>:i</code> in the same position means &quot;Intel Hex&quot;</p> <p>A complete list can be found here: <a href="https://www.nongnu.org/avrdude/user-manual/avrdude_3.html#Option-Descriptions" rel="nofollow noreferrer">https://www.nongnu.org/avrdude/user-manual/avrdude_3.html#Option-Descriptions</a></p>
92125
|serial|arduino-nano|
Serial port stops receiving data after random amount of time
2023-01-31T11:23:26.097
<p>EDIT: Things I have tried so far:</p> <ol> <li><p>Increasing the baud rate, but this didn't make any difference as it still continued to stop receiving data after random amount of time.</p> </li> <li><p>I tried testing one sensor and reducing the sketch to something that only prints in a sketch. I can get the sketch to work up to 2 sensors where it prints the results continuously. 3 or 4 sensors and I get the issue mentioned.</p> </li> </ol> <p>Link to the VL53L4CD library: <a href="https://github.com/stm32duino/VL53L4CD" rel="nofollow noreferrer">https://github.com/stm32duino/VL53L4CD</a></p> <p>Datasheets:</p> <p><a href="https://cdn-learn.adafruit.com/downloads/pdf/adafruit-vl53l4cd-time-of-flight-distance-sensor.pdf" rel="nofollow noreferrer">https://cdn-learn.adafruit.com/downloads/pdf/adafruit-vl53l4cd-time-of-flight-distance-sensor.pdf</a></p> <p><a href="https://www.st.com/resource/en/datasheet/vl53l4cd.pdf" rel="nofollow noreferrer">https://www.st.com/resource/en/datasheet/vl53l4cd.pdf</a></p> <hr /> <p>I'm currently working on a project where I need to measure distances at two different points using distance sensors (I'm currently using VL53L4CD laser distance sensors). However, this project requires a high sampling rate of 100Hz. To achieve this, I have 4 distance sensors arranged into 2 sensor sets. Each sensor set consists of 2 distance sensors (So for example, sensor set 1 consists of distance sensor 2&amp;3 and sensor set 2 consists of distance sensor 1&amp;4) and I would alternate between reading each sensor set.</p> <p>This seemed to work at first, I did get a new distance reading every 8ms. However, the serial port stops receiving the distance readings after a very random amount of time. Sometimes the serial port stops receiving new data after 5 seconds, sometimes 30s, sometimes 60 and even 180s.</p> <p>I'm not sure what's causing this issue what I can do to fix it. Any help is appreciated (I'm using the Arduino Nano 33 IOT)</p> <p>Thanks!</p> <p>Here is my code below:</p> <pre><code>// Included libraries #include &lt;Arduino.h&gt; #include &lt;Wire.h&gt; // Libraries required for VL53L4CD sensors #include &lt;vl53l4cd_class.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;assert.h&gt; #include &lt;stdlib.h&gt; // Definitions #define DEV_I2C Wire #define SerialPort Serial // variables int alternate = 0; // Variable used to alternate between sensor sets // Components. VL53L4CD sensor_vl53l4cd_1(&amp;DEV_I2C, 2); // xshut pin of distance sensor 1 connected to pin 2 VL53L4CD sensor_vl53l4cd_2(&amp;DEV_I2C, 3); // xshut pin of distance sensor 2 connected to pin 3 VL53L4CD sensor_vl53l4cd_3(&amp;DEV_I2C, 5); // xshut pin of distance sensor 3 connected to pin 5 VL53L4CD sensor_vl53l4cd_4(&amp;DEV_I2C, 6); // xshut pin of distance sensor 4 connected to pin 6 /* Setup ---------------------------------------------------------------------*/ void setup() { // DISTANCE SENSOR SETUP // Initialize serial for output. SerialPort.begin(9600); SerialPort.println(&quot;Starting...&quot;); // Initialize I2C bus. DEV_I2C.begin(); // Configure VL53L4CD number 1 Serial.println(&quot;Configuring distance sensor 1&quot;); sensor_vl53l4cd_1.begin(); sensor_vl53l4cd_1.VL53L4CD_Off(); sensor_vl53l4cd_1.InitSensor(); sensor_vl53l4cd_1.VL53L4CD_SetI2CAddress(0x40); sensor_vl53l4cd_1.VL53L4CD_SetRangeTiming(10, 0); // Configure VL53L4CD number 2 Serial.println(&quot;Configuring distance sensor 2&quot;); sensor_vl53l4cd_2.begin(); sensor_vl53l4cd_2.VL53L4CD_Off(); sensor_vl53l4cd_2.InitSensor(); sensor_vl53l4cd_2.VL53L4CD_SetI2CAddress(0x42); sensor_vl53l4cd_2.VL53L4CD_SetRangeTiming(10, 0); // Configure VL53L4CD number 3 Serial.println(&quot;Configuring distance sensor 3&quot;); sensor_vl53l4cd_3.begin(); sensor_vl53l4cd_3.VL53L4CD_Off(); sensor_vl53l4cd_3.InitSensor(); sensor_vl53l4cd_3.VL53L4CD_SetI2CAddress(0x44); sensor_vl53l4cd_3.VL53L4CD_SetRangeTiming(10, 0); // Configure VL53L4CD number 4 Serial.println(&quot;Configuring distance sensor 4&quot;); sensor_vl53l4cd_4.begin(); sensor_vl53l4cd_4.VL53L4CD_Off(); sensor_vl53l4cd_4.InitSensor(); sensor_vl53l4cd_4.VL53L4CD_SetI2CAddress(0x46); sensor_vl53l4cd_4.VL53L4CD_SetRangeTiming(10, 0); // Start Measurements sensor_vl53l4cd_1.VL53L4CD_StartRanging(); sensor_vl53l4cd_2.VL53L4CD_StartRanging(); sensor_vl53l4cd_3.VL53L4CD_StartRanging(); sensor_vl53l4cd_4.VL53L4CD_StartRanging(); } void loop() { // Read results from sensor set 1 if (alternate == 0){ VL53L4CD_Result_t results2; VL53L4CD_Result_t results3; // Read results from sensor set 1 (Sensors 2 and 3) sensor_vl53l4cd_2.VL53L4CD_ClearInterrupt(); sensor_vl53l4cd_2.VL53L4CD_GetResult(&amp;results2); sensor_vl53l4cd_3.VL53L4CD_ClearInterrupt(); sensor_vl53l4cd_3.VL53L4CD_GetResult(&amp;results3); Serial.print(&quot;Distance 1-1 = &quot;); Serial.print(results2.distance_mm); Serial.println(&quot; &quot;); Serial.print(&quot;Distance 1-2 = &quot;); Serial.print(results3.distance_mm); Serial.println(&quot; &quot;); alternate = 1; // Change value so sensor set 2 is read in the following loop } // Read results from sensor set 2 else if (alternate == 1){ VL53L4CD_Result_t results1; VL53L4CD_Result_t results4; // Read results from sensor set 1 (Sensors 1 and 4) sensor_vl53l4cd_1.VL53L4CD_ClearInterrupt(); sensor_vl53l4cd_1.VL53L4CD_GetResult(&amp;results1); sensor_vl53l4cd_4.VL53L4CD_ClearInterrupt(); sensor_vl53l4cd_4.VL53L4CD_GetResult(&amp;results4); Serial.print(&quot;Distance 2-1 = &quot;); Serial.print(results1.distance_mm); Serial.println(&quot; &quot;); Serial.print(&quot;Distance 2-2 = &quot;); Serial.print(results4.distance_mm); Serial.println(&quot; &quot;); alternate = 0; // Change value so sensor set 2 is read in the following loop } Serial.println(millis()); } </code></pre>
<p>I tried powering all of the sensors with an external power source and this seems to solve the issue, I got consistent readings from all the distance sensors and the serial port did not stop receiving data. It might have been the USB port on my laptop that was causing these issues.</p>
92126
|serial|usb|communication|7-segment|
Arduino MEGA - How to send and receive data asynchronously?
2023-01-31T11:38:05.900
<p>i am newbie to this so i hope i can explain my problem clearly;</p> <p>Arduino MEGA connected to PC via USB port.</p> <p>I am using an encoder to trigger function to send data to pc, data is a simple string &quot;A01&quot; or &quot;A02&quot; when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like &quot;MCPHDGxxx&quot; and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display. (xxx is a number between 000 and 359, and that number changes on PC screen when arduino send &quot;A01&quot; or &quot;A02&quot; string to PC)</p> <p>When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that &quot;number&quot; data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.</p> <p>Is it possible to make it work asynchronously?</p> <p>Here is my sketch:</p> <pre><code>#include &quot;DigitLedDisplay.h&quot; #define outputA 24 #define outputB 25 int aState; int aLastState; unsigned long lastButtonPress = 0; long finalMCPHDGLong; String ReceivedSerialString; DigitLedDisplay ld = DigitLedDisplay(21, 22, 23); void setup() { pinMode (outputA,INPUT); pinMode (outputB,INPUT); Serial.begin (115200); // Reads the initial state of the outputA aLastState = digitalRead(outputA); /* Set the brightness min:1, max:15 */ ld.setBright(10); /* Set the digit count */ ld.setDigitLimit(8); } void loop() { aState = digitalRead(outputA); // Reads the &quot;current&quot; state of the outputA // If the previous and the current state of the outputA are different, that means a Pulse has occured if (aState != aLastState){ // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise if (digitalRead(outputB) != aState) { if (millis() - lastButtonPress &gt; 25) { Serial.println(&quot;A01&quot;); } // Remember last button press event lastButtonPress = millis(); } else { if (millis() - lastButtonPress &gt; 25) { Serial.println(&quot;A02&quot;); } // Remember last button press event lastButtonPress = millis(); } } aLastState = aState; while (Serial.available() &gt; 0){ ReceivedSerialString = Serial.readString(); if (ReceivedSerialString.substring(0,6) == &quot;MCPHDG&quot;){ String value = ReceivedSerialString.substring(6,9); long val = value.toInt(); finalMCPHDGLong = val; if((finalMCPHDGLong &lt;= 99)){ ld.printDigit(0,7); }if((finalMCPHDGLong &lt;= 9)){ ld.printDigit(0,6); } ld.printDigit(val, 5); } } } </code></pre>
<blockquote> <p>Seems like receiving data from PC blocking my send data function until it's done.</p> </blockquote> <p>You may be saying the same thing, but I'd put it that it's waiting for more data to arrive that isn't going to.</p> <blockquote> <p>Is it possible to make it work asynchronously?</p> </blockquote> <p>Depending on how you're defining &quot;asynchronously&quot; that may be unnecessary.</p> <pre class="lang-cpp prettyprint-override"><code>while (Serial.available() &gt; 0){ if (ReceivedSerialString.substring(0,6) == &quot;MCPHDG&quot;){ String value = ReceivedSerialString.substring(6,9); </code></pre> <p>There's a lot that could be said about using <code>String</code> and conversion to <code>int</code> and choosing a simple message format and so forth, but I'll elide most of that. Finding a good approach to what you're doing would require understanding a lot more about what you're doing and why. But, taking your code and question as written, the <strong>main thing is that <code>readString()</code> here is terminating based on the value of <code>Serial.setTimeout()</code>, which by default is <code>1000</code> or 1 second. So you are spending a lot of time doing nothing following receipt of your command from the PC. So during that 1 second you are not tending to the &quot;encoder&quot;.</strong></p> <p>You could play with <code>setTimeout</code>, but it would be better to avoid a timeout altogether by not attempting to read when there's no more command to be read. If this protocol you're using is line-oriented then you have a terminator you can use in the form of '\r' or '\n'. This can be done with <code>Serial.readStringUntil(whatever_your_terminator_is);</code> If you have both '\r' and '\n' you will need to read other part of the termination sequence and then throw it away. Either it will come in as part of the read string or it will not and you will need to do a second read to discard it. There are more sophisticated ways to go about this, but that maybe sufficient for what you're doing.</p> <p>When it comes to not blocking (or significant blocking) of serial reads, you have to assure that the data is there to be read. Either because you know it's sent (and are willing to trust that it was received okay). Or you use <code>Serial.setTimeout</code> with a 0 or sufficiently small number, <code>.read()</code> indicates no data with a negative return value, or by checking <code>.available()</code>, and it all of these cases deciding what to do when you have not received everything, or everything... yet. Doing it well, manually, is a bit of a pain.</p> <p>For writing/printing to serial there's a counterpart <code>.availableForWrite()</code> which you can use to determine ahead of time whether or not you're going to be stuck in waiting (in <code>.print()</code>/<code>.println()</code>/<code>.write()</code>) for the serial data to go out, in turn not tending to the encoder. Basically you can choose where and how to throttle your writing to serial so as not overly interfere checking the encoder rather than causing throttle to happen within <code>Serial.write</code>. With the way your code is currently written, with events coming in at the rate they apparently are (according to your debouncing code) this is probably not currently a problem for you. But it's worth keeping in mind if you begin handling events at a higher rate. Placing a character in the outbound serial buffer is significantly faster than waiting for space for a character to become available in the serial buffer.</p>
92139
|arduino-uno|motor|stepper|speed|a4988|
Need help figuring out how to organise a system to run a stepper motor at low speed without Steps-skipping
2023-02-01T13:02:36.173
<p>TL;DR : How to prevent step-skipping with a NEMA gearbox motor at low speed.</p> <p>I am in the process of creating a system in which I want an object to turn on a plate and to show a letter depending on the angle of the rotation. The object is quite heavy hence the rotation should be quite slow, this is why I took a Planetary Gearbox NEMA Stepper.</p> <p>My system consists in:</p> <ul> <li>An Arduino Uno</li> <li><a href="https://www.amazon.de/dp/B077YXF759?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details" rel="nofollow noreferrer">A NEMA Stepper Motor</a></li> <li><a href="https://www.amazon.de/dp/B083V59HTB?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details" rel="nofollow noreferrer">A A4988 Driver</a></li> <li>Some wires</li> <li>2 Iron plates</li> <li><a href="https://www.amazon.de/dp/B0B98YSRQS?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details" rel="nofollow noreferrer">A ball bearing element in between the Iron plates</a></li> <li>Screws to fit everything together.</li> </ul> <p>This is the code I ended up with:</p> <pre><code>// Define stepper motor connections and steps per revolution: #define dirPin 6 #define stepPin 7 #define stepsPerRevolution 5373 int degree_init = 1; int mouvement=0; // create a mapping between letters and degrees int letterToDegree[33] ; int degree; // function to map letters to degrees int mapLetterToDegree(char letter) { if (letter=='.'){ return letterToDegree[27]; } else if (letter==':'){ return letterToDegree[28]; } else if (letter==&quot;\'&quot;){ return letterToDegree[29]; } else if (letter==' '){ return letterToDegree[30]; } else { int letterIndex = letter - 'A'; // get the index of the letter in the alphabet return letterToDegree[letterIndex]; // return the degree associated with that letter } } void setup() { // Declare pins as output: pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); Serial.begin(9600); for (int i = 0; i &lt; 33; i++){ letterToDegree[i]= degree_init; degree_init=degree_init+10; } } void loop() { int p= NULL; // Set the spinning direction clockwise: digitalWrite(dirPin, HIGH); String input= &quot;NOW THE NOW THE AAAAA&quot;; // loop through the letters for (int i = 0; i &lt; input.length(); i++) { // get the degree for each letter degree = mapLetterToDegree(input[i]); Serial.print(&quot;Letter: &quot;); Serial.print(input[i]); Serial.print(&quot; Degrees: &quot;); Serial.println(degree); // wait for the movement to complete delay(1000); int p_new= map(degree,0,360,0,5373); Serial.print(&quot; position: &quot;); Serial.println(p_new); if (p!=NULL){ mouvement=p_new-p; p=p_new; Serial.print(&quot; mouvement: &quot;); Serial.println(mouvement); } else{ p = p_new; } if (mouvement&lt;0){ digitalWrite(dirPin, LOW); mouvement=abs(mouvement); Serial.println(&quot;change de direction&quot;); } Serial.print(&quot; stepper: &quot;); Serial.println(mouvement); // Spin the stepper motor 1 revolution slowly: for (int i = 0; i &lt; mouvement; i++) { // These four lines result in 1 step: digitalWrite(stepPin, HIGH); delay(20); digitalWrite(stepPin, LOW); delay(20); } delay(1000); digitalWrite(dirPin, HIGH); } } </code></pre> <p>I tried following <a href="https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/" rel="nofollow noreferrer">this tutorial</a> and it works in broad terms <strong>but sometimes the motor skips steps, especially when changing direction.</strong></p> <p>I can't seem to understand how torque works within this system and how to minimise the stress I put on the motor. My hypothesis is that since the system is at equilibrium and the friction is minimised due to the ball bearing, there should be no need for a lot of power from the motor, and that this motor should suffice.</p> <p>My hypothesis of why steps are skipped:</p> <ul> <li>Too high a speed for the motor</li> <li>Not enough torque power supplied</li> <li>Not good enough electricity supply to the motor.</li> </ul> <p>I am not sure how to go about and test these hypothesis and if those are correct. I am also having a lot of trouble understanding the relationship between the time delay in the code and the movement of the motor.</p> <p>Especially this bit:</p> <pre><code> for (int i = 0; i &lt; mouvement; i++) { // These four lines result in 1 step: digitalWrite(stepPin, HIGH); delay(20); digitalWrite(stepPin, LOW); delay(20); } </code></pre> <p>Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?</p> <p>I am also looking for an explanation of how to apply acceleration and decceleration algorithms for stepper motor, even though I am not sure it makes sense at this speed.</p> <p><strong>My questions are:</strong></p> <ul> <li>How to calculate the best speed for such a system and how to implement it?</li> <li>Is there need for acceleration/ decceleration?</li> <li>Does microstepping makes sense when using a gearbox?</li> <li>Are there some obvious flaws in my system/ code that I am missing out?</li> </ul> <p><a href="https://i.stack.imgur.com/gOyRh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gOyRh.jpg" alt="Arduino and Driver" /></a> <a href="https://i.stack.imgur.com/zpbeT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpbeT.jpg" alt="stepper and ball bearing plate" /></a> <a href="https://i.stack.imgur.com/r9STh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r9STh.jpg" alt="Behaviour description" /></a> <a href="https://i.stack.imgur.com/p4YUy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p4YUy.jpg" alt="System description" /></a></p>
<blockquote> <p>How to calculate the best speed for such a system and how to implement it?</p> </blockquote> <p>There is no one best speed. This depends on your requirements, the motor torque with the supplied power and driver and the rotational inertia of the object on the motor axis. You can measure the rotational inertia and set yourself a value for the acceleration (even if you don't write the program for acceleration, it will accelerate on the first steps), that you want to have. Then you can check, if your motor has enough torque for this.</p> <p>Speaking about the motor: Check the ratings of the motor. A good supplier should also give you information on how much torque your motor has at specific currents. Then check if your driver can handle the current (these small stick drivers often cannot handle much current, like 1 or 2A max). These drivers also have a small potentiometer on board, which controls the motor current. Your supplier should also provide information on how to set it correctly (by checking the voltage on one of the pins). You can even find information about this online, when you search for your type of driver. Setting this wrong can lead to either an underperforming motor or the motor overheating. So when setting the motor current with the potentiometer, check the motor temperature afterwards while it is running. Every motor has its own temperature rating, but I would suggest not letting it get too hot to touch.</p> <p>Having done all above you can drive a test for checking motor speeds. Forget about your current code for a while. Just drive the motor with specific speeds, starting from only a few steps per second and going up until you notice the motor skipping. Then you know how fast you can drive the motor in your configuration without skipping and acceleration. If that is fast enough for you, you can just stick to that.</p> <blockquote> <p>Is there need for acceleration/ decceleration?</p> </blockquote> <p>That depends on the above. If the non-skip speed is not fast enough, you can accelerate by gradually increasing the steps per second (aka decreasing the delay between step pulses). To halt at a specific position you then need to decelerate, so you need to plan the movement and control the steps per second accordingly. If you don't want to do that yourself I would suggest using the <code>AccelStepper</code> library. There you can set the target speed and the maximum acceleration and the library will then handle the motor for you.</p> <p>You wrote in a comment, that you tried the <code>AccelStepper</code> library and that it didn't help. Though you didn't state how exactly it didn't help and what exactly you tried. Maybe you just didn't use the library correctly.</p> <blockquote> <p>Does microstepping makes sense when using a gearbox?</p> </blockquote> <p>With microstepping you can get a smoother movement, though I doubt, that this is the problem here. Activating microstepping will of course mean, that you need to send more pulses to the driver for the same speed. Just keep that in mind.</p> <blockquote> <p>Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?</p> </blockquote> <p>The first delay establishes the pulse for the driver. It needs to be big enough, that the driver recognizes the pulse. 20ms is very long for that. If you look at the datasheet of the your driver chip, there should be some information on that. I used a delay of about 50us in the past (so <code>delayMicroseconds(50)</code>), though you might even get shorter.</p> <p>The second delay then handles the time between pulses, aka the speed of the motor. Though keep in mind, that the first delay is also still a constant in that equation. The speed in steps per second would then be <code>1/(delay1+delay2)</code> (ignoring the time for the execution of the rest of the code, because only relevant at high speeds).</p>
92173
|analog|
Why is my analog output limited to 2.7V?
2023-02-04T13:13:45.643
<p>I have an MKR WIFI1000 (v2.0 [Arduino:XYZ]) with a &quot;real&quot; analog output pin (DAC0/A0/PIN15). According to the documentation, this is a 10 bit DAC, so I assume I can write <code>analogWrite(15, 1023)</code> to have an output of 3.3V on that pin.</p> <p>However, I don't seem to get it higher than 2.7V, which is already reached well before a value of 256.</p> <p>This is my code:</p> <pre><code>#include &lt;Arduino.h&gt; #define AN_OUTPUT 15 int counter = 0; void setup() { pinMode(AN_OUTPUT, OUTPUT); } void loop () { counter++; if (counter &gt; 1023) { counter = 0; } analogWrite(AN_OUTPUT, counter); delayMicroseconds(1); } </code></pre> <p>And this is the corresponding signal:</p> <p><a href="https://i.stack.imgur.com/qA4Ry.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qA4Ry.jpg" alt="enter image description here" /></a></p>
<p><a href="https://learn.adafruit.com/adafruit-feather-m0-basic-proto/adapting-sketches-to-m0" rel="nofollow noreferrer">This link</a> had the answer, you have to <strong>remove</strong> the <code>pinMode(PIN, OUTPUT)</code> line.</p>
92175
|arduino-ide|
Tools > Board settings: how are they captured?
2023-02-04T13:55:36.760
<p>In the Arduino IDE, the Tools menu can be used to make some board-specific settings like this:</p> <p><a href="https://i.stack.imgur.com/EYfvU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EYfvU.png" alt="enter image description here" /></a></p> <p>... such as Processor Version = &quot;Atmega168P&quot;, Processor Speed = &quot;16MHz Crystal Resonator&quot; and so on. These end up choosing fuses when burning a bootloader. They may or may not also set constants that influence library behavior, I'm not sure.</p> <p>What I'd like to know is how such settings stored, as they don't seem to be stored in any file associated with the sketch. And that being the case, they seem to be lost when using different boards or settings for subsequent projects.</p> <p>So what files store these settings, at least temporarily, and how might one associate those settings more permanently with the project/sketch, so that they are repeatable later?</p>
<p>The board settings from Tools menu are stored in the IDE preferences file.</p> <p>You can open the file from the Preference dialog of the Arduino IDE. The path to the file is shown at the bottom of the dialog and it is clickable.</p>
92217
|arduino-uno|programming|led|rgb-led|error|
RGB LED randomized colors and LDR fading at the same time
2023-02-08T15:46:21.987
<p>Im trying too make an RGB LED that keeps changing color's randomly, and makes the brightness fade at the same time with an LDR, yet I keep getting an error that says too many arguments to functions.</p> <p>could anyone possibly help me?</p> <p>EDIT: (this is the correct code sorry)</p> <pre><code> const int LED_D_RGB_G_PIN = 11; const int LED_D_RGB_B_PIN = 10; const int LED_D_RGB_R_PIN = 9; const int LDR = A1; int inputval=0; int outval =0; void setup() { pinMode(LED_D_RGB_R_PIN, OUTPUT); pinMode(LED_D_RGB_G_PIN, OUTPUT); pinMode(LED_D_RGB_B_PIN, OUTPUT); pinMode(LDR, INPUT); } void loop() { inputval = analogRead(LDR); outval = map(inputval, 0, 380, 255, 0); int lightval = constrain(outval, 0,255); analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255)); analogWrite(LED_D_RGB_G_PIN, lightval, random(0,255)); analogWrite(LED_D_RGB_B_PIN, lightval, random(0,255)); delay (50); } </code></pre>
<p>I will assume that you can correct any errors in your code and I want to get at a suggestion for a possibly better approach to what I think that you are trying to do.</p> <p>When you are setting the &quot;color&quot;, you are setting the brightness of each of the LEDs; R,G,B, or at least you are trying to do that when you generate a random PWM using analogWrite <a href="https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/</a>.</p> <p>Then, you are trying to set the brightness again, presumably based on the ambient light value from the LDR AND it is set for the <strong>combined</strong> output of the 3 LEDs which are likely at different intensity values, since intensity was randomly chosen. The problem is, how can you scale the values perfectly so that you get the same color but at a lower intensity? I think that is much more difficult than you might believe...for a bunch of reasons.</p> <p>I would suggest you try something along these lines, but keep some low expectations....</p> <ol> <li><p>Use a variable called maxb, which changes the <strong>maximum possible</strong> value used in the analogWrite() values so that it it not always 255. You can adjust that value based on reading the LDR. You will have to do some experimenting and don't expect a huge range of values. Now, your color will still be picked at random, but with an adjustment for intensity.</p> </li> <li><p>You <em>&quot;should&quot;</em> try to use resistors on each of the RGB LEDs that will produce something close to equivalent brightness. This will vary somewhat between RGB LEDs. Below is a graph of where I looked at this for a color fader project many years ago. I used an old BH1750 ambient light sensor to get the lux values. That dashed line is for the equivalent brightness of the individual LEDs by resistor value (ohms) used [220-Red, 750-Green, 470-Blue]. This is not an ideal way, but it is easy.</p> </li> </ol> <p><a href="https://i.stack.imgur.com/hQOLq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hQOLq.jpg" alt="enter image description here" /></a></p> <ol start="3"> <li>That might get you near where you want to be, but for &quot;extra credit&quot;, note that brightness scaling is not an equal interval scale. So, a PWM value of 250 is NOT 10 times brighter than a PWM value of 25. Brightness is, more or less, on an exponential scale except for very dim values, which are, again, more-or-less, linear. Look into the CIE 1931 perceived lightness formula and Weber and Stevens and so on. Since this is not a psychophysics lab, let me cut to the chase. The array below represents an intensity scale as I have described and includes values of 0 and 255 as per an 8 bit width (which is what analogWrite uses). You could use a minimum value of 4 or 8 instead of 0 if you wanted to guarantee a visible output every time. Test that out, but for the sake of discussion, let's assume you are using all values in the array.</li> </ol> <p>A[13]{0,1,2,4,8,17,32,51,75,106,145,194,255};</p> <p>You would scale your LDR range to 13 possible values (0-12) and then get your maximum value for analogWrite from the array. Then, you would pick a random value for 0 to maxb for each of your analogWrites to the RGB.</p> <ol start="4"> <li>I don't know how brightness is represented by your LDR and you should consider that when you are determining your ambient light intensity values - ideally, you would want 13 equal intensity values from your LDR - right?. I suppose something about that is probably in the data sheet.</li> </ol> <p>That is how I would do it anyways :)</p>
92226
|c++|header|pinmode|
Setting pinmode() in header file
2023-02-09T15:40:41.433
<p>I am trying to have a header file to handle all my pin definitions and pinmodes.</p> <p>This is the header:</p> <pre><code>#ifndef __HEADER_TESTER__ #define __HEADER_TESTER__ #include &lt;SoftwareSerial.h&gt; const byte rxPin = 2; const byte txPin = 3; SoftwareSerial mySerial(rxPin, txPin); pinMode(LED_BUILTIN, OUTPUT); #endif </code></pre> <p>However, when I compile this, I get an error on the <code>pinMode(LED_BUILTIN, OUTPUT);</code> line:</p> <pre><code>expected constructor, destructor, or type conversion before '(' token </code></pre>
<p>The <code>pinMode()</code> statement is executable code and can not be executed outside of a function - setup(), loop(), or some other function defined by you. One could imagine defining a function in your header (.h) file to set your pin modes but defining code in a header will cause a different kind of problem (multiple definitions) if you ever add another code module, a .cpp file, for instance, that also includes this same .h file.</p> <p>Pin modes are usually set in the setup() function, once per execution of the sketch. There really isn't much value to having them in the .h file. If it is for documentation purposes, you could #define in the .h file, a symbol that expands to all of the pinMode() calls you need, then write that symbol at the appropriate place in your setup() function where it's expansion will be syntactically correct. This would accomplish the documentation, but at the cost of a reader of your code having to search for the definition of that symbol to find out what code is being executed there. That's pretty roundabout for what seems like little to no gain.</p>
92228
|arduino-nano|
How to connect Arduino Nano to Thermal Printer via serial connection
2023-02-09T18:00:46.673
<p>I have a generic Arduino Nano board that uses the old bootloader. I have the printer and the Arduino connected like so:</p> <p><a href="https://i.stack.imgur.com/ZJgdT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZJgdT.png" alt="enter image description here" /></a></p> <p>This is my code:</p> <pre><code>#include &quot;Adafruit_Thermal.h&quot; // Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ---- // If using hardware serial instead, comment out or remove these lines: #include &quot;SoftwareSerial.h&quot; #define TX_PIN 5 // Arduino transmit YELLOW WIRE labeled RX on printer #define RX_PIN 6 // Arduino receive GREEN WIRE labeled TX on printer SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first Adafruit_Thermal printer(&amp;mySerial); // Pass addr to printer constructor // Then see setup() function regarding serial &amp; printer begin() calls. // Here's the syntax for hardware serial (e.g. Arduino Due) -------------- // Un-comment the following line if using hardware serial: //Adafruit_Thermal printer(&amp;Serial1); // Or Serial2, Serial3, etc. // ----------------------------------------------------------------------- void setup() { // This line is for compatibility with the Adafruit IotP project pack, // which uses pin 7 as a spare grounding point. You only need this if // wired up the same way (w/3-pin header into pins 5/6/7): // pinMode(BUILTIN, OUTPUT); digitalWrite(7, LOW); // NOTE: SOME PRINTERS NEED 9600 BAUD instead of 19200, check test page. mySerial.begin(9600); // Initialize SoftwareSerial //Serial1.begin(19200); // Use this instead if using hardware serial printer.begin(); // Init printer (same regardless of serial type) // The following calls are in setup(), but don't *need* to be. Use them // anywhere! They're just here so they run one time and are not printed // over and over (which would happen if they were in loop() instead). // Some functions will feed a line when called, this is normal. // Font options printer.setFont('B'); printer.println(&quot;FontB&quot;); printer.println(&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;); printer.setFont('A'); printer.println(&quot;FontA (default)&quot;); printer.println(&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;); printer.sleep(); // Tell printer to sleep delay(3000L); // Sleep for 3 seconds printer.wake(); // MUST wake() before printing again, even if reset printer.setDefault(); // Restore printer to defaults } void loop() { } </code></pre> <p>When I run my code or reset no prints get sent to the print.</p> <p>Here's what I've tried.</p> <ul> <li>Ensure power is on on both devices</li> <li>Try baud rate 19200</li> <li>Swop Tx and Rx cables around</li> <li>Tried D5 and D6 for Tx and Rx</li> </ul> <p>Any help would me much appreciated.</p>
<p>Your additional info about your printer tells me that it has a Bluetooth and a USB interface - but I can not see any other serial connection port.</p> <p>So there is no way connecting this printer as-is to the arduino nano by some digital port pins.</p> <p>You may decide to either buy the Thermal printer offered by Adafruit our search for a Thermal printer that clearly states that is has a &quot;Serial Interface&quot; or &quot;Serial RS232 Interface&quot; - no matter if that comes with &quot;TTL&quot; or not like the Adafruit printer.</p> <p>The printer is intended to be connected to a USB host port (of an PC or RPi or so) or via Bluetooth (to an PC or Android phone).</p> <p>It may offers a virtual serial interface over both USB and Bluetooth, but that is a speculation.</p> <p><em>It may be possible to hack your printer. I think the Adafruit printer was modded by Adafruit. They may have bought a stock-printer and added the connector for the TTL interface. This may also be possible with the printer you have, but that is not in the scope of your question and highly speculative.</em></p>
92229
|arduino-nano|arduino-nano-ble|watchdog|
How to configure watchdog for the arduino Nano 33 BLE Sense board?
2023-02-09T21:42:49.257
<p>For the arduino Nano 33 BLE Sense board, the standard <code>avr/wdt.h</code> is not available. And it seems that no standard library provides it. How to use the watchdog system for this board ? I found no full information about it.</p> <p>I've found the page <a href="https://www.mysensors.org/apidocs/group__avr__watchdog.html" rel="nofollow noreferrer">https://www.mysensors.org/apidocs/group__avr__watchdog.html</a> which allow to configure the reboot mode. And it works. But no way to configure the interruption mode with <code>ISR()</code> function. Moreover, there's no explanation about the manipulation of used register/variables for any fine configuration.</p> <p>Simple code example with regular asynchronous stuff using the watchdog ISR() mechanism. It which works well with ATmega328 (e.g.UNO). But I do not find equivalent configuration for the Nano 33 BLE using the nRF52840.</p> <pre><code># include &lt;avr/wdt.h&gt; volatile byte led; int k; ISR(WDT_vect) { Serial.println(&quot;Asynchronous stuff in ISR() function&quot;); digitalWrite(LED_BUILTIN,led); led=!led; } void setup() { pinMode(LED_BUILTIN,OUTPUT); led=0; Serial.begin(9600); while(!Serial) {} Serial.println(&quot;== R E B O O T ==&quot;); WDTCSR = ( 1 &lt;&lt; WDE ) | ( 1 &lt;&lt; WDCE ); WDTCSR = ( 1 &lt;&lt; WDP2 ) | ( 1 &lt;&lt; WDP0 ) | ( 1 &lt;&lt; WDIE ) ; // Interruption and timeout 1/2 s } void loop() { Serial.print(&quot;Loop #&quot;); Serial.println(k); if (k++%2) { Serial.println(&quot;Some stuff (even branch)&quot;); delay(1200); } else { Serial.println(&quot;Some stuff (odd branch)&quot;); delay(4800); } } </code></pre> <p>Thks.</p>
<p>In fact, for the RF52940, I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc <a href="https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf" rel="nofollow noreferrer">https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf</a>). But the good way is for sure the use of timers (and one can use more than just one, quite good).</p> <p>For a similar behaviour as the code given for the UNO before, here is the code one can write for the Nano BLE using a timer interrupt (see <a href="https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt" rel="nofollow noreferrer">https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt</a> for full and usefull doc).</p> <pre><code>#include &quot;NRF52_MBED_TimerInterrupt.h&quot; volatile byte led; volatile uint32_t count=0; NRF52_MBED_Timer myTimer(NRF_TIMER_1); unsigned k=0; void myHandler() { digitalWrite(LED_BUILTIN,led); led=!led; count++; } void setup() { pinMode(LED_BUILTIN,OUTPUT); led=0; Serial.begin(9600); while(!Serial) {} Serial.println(&quot;== R E B O O T ==&quot;); if (myTimer.attachInterruptInterval(500*1000, myHandler)) // each 1/2 second Serial.println(&quot;myTimer launched&quot;); else Serial.println(&quot;Can not set the timer&quot;); } void loop() { Serial.print(&quot;Loop #&quot;); Serial.print(k); Serial.print(&quot; and nb times in Handler : &quot;); Serial.println(count); if (k++%2) { Serial.println(&quot;Some stuff (even branch)&quot;); delay(1200); } else { Serial.println(&quot;Some stuff (odd branch)&quot;); delay(4800); } } </code></pre>
92240
|timing|
delayMIcroseconds and micros execution time not explainable
2023-02-10T22:44:48.633
<p>i just experimented with the timing accuracy of my Arduino Uno R3 using this code:</p> <pre><code>unsigned long beginTime; unsigned long endTime; void setup() { Serial.begin(9600); // open a serial port } void loop() { beginTime = micros(); delayMicroseconds(200); endTime = micros(); delay(500); Serial.println(endTime-beginTime); delay(500); } </code></pre> <p>The results I got are (just an excerpt):</p> <pre><code>200 204 200 200 204 204 204 200 212 208 212 204 204 </code></pre> <p>I tried to understand this behavior, read this link <a href="https://arduino.stackexchange.com/questions/37387/can-i-make-delaymicroseconds-more-accurate">Can I make delayMicroseconds more accurate?</a>.</p> <p>Due to the timing of <code>micros</code> (4 µs) I would understand values between 200 and 208. <strong>But why do I get occasional values of 212 microseconds?</strong> I'm kinda curious, since I bought the Arduino because of bare-metal programming and bounded execution times.</p>
<p>The Arduino core uses hardware Timer0 with its ISR (Interrupt Service Routine) for timekeeping. While <code>delayMicroseconds()</code> directly uses the value of the hardware timer, <code>delay()</code> and <code>millis()</code> are handled by the ISR. It will be called regularly.</p> <p>If the ISR is getting executed during your measurement, then the execution time of the ISR will add to the execution time of your measured code. Thus you get a higher count occasionally.</p> <p>To prevent this you can either deactivate all interrupts (via <code>noInterrupts()</code>) or deactivate this specific interrupt, either by stopping Timer0:</p> <pre><code>TCCR0B &amp;= ~( (1 &lt;&lt; CS02) | (1 &lt;&lt; CS01) | (1 &lt;&lt; CS00) ); </code></pre> <p>or by letting the timer run, but deactivating its interrupts:</p> <pre><code>TIMSK0 = 0; </code></pre> <p>For details about this have a look at the <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf" rel="nofollow noreferrer">datasheet of the Atmega328p</a>, which is the microcontroller on the Arduino Uno.</p>
92244
|watchdog|arduino-mkr|
Why is the watchdog biting to quickly?
2023-02-11T10:53:20.287
<p>currently trying to implement a watchdog into my project. I am using the WDTZero library for controlling the watchdog on my MKR NB 1500. The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Sometimes the code can hang if it can't connect to the NTP server or the server on which the data is being stored, I want the watchdog to reset the program in cases in which this happens.</p> <p>A sketch of the program is below. The reason why the NB network is often after different connections is that the NB 1500 is not able to connect to another server if the GPRS connection is already open, so I always reset it before trying another connection.</p> <pre><code>void setup() { setup_watchdog(); //Sets up the watchdog timer delay(1000); connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway) set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time disconnect_NB(); //Disconnects from the NB network delay(2000); MyWatchDoggy.clear(); //Resets the watchdog timer } void loop() { connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection get_ENV_data(); //Takes measurements using the MKR NB ENV shield connect_to_server(); //Connects to the server in which the data will be stored write_to_server(); //Writes the data on the server disconnect_from_server(); //Disconnects from the server disconnect_NB(); //Disconnects from the NB network LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes delay(3000); MyWatchDoggy.clear(); //Resets the watchdog timer } </code></pre> <p>All the functions above are written in other .cpp files and imported thru header files into the main file. Here is the code for activating and configuring the watchdog:</p> <pre><code>#include &quot;watchdog.hpp&quot; #include &quot;GPRS_NB_connection.hpp&quot; WDTZero MyWatchDoggy; void setup_watchdog() { MyWatchDoggy.attachShutdown(NVIC_SystemReset); //calls reset function MyWatchDoggy.setup(WDT_SOFTCYCLE8M); //8 minute watchdog timer } </code></pre> <p>The program works fine in the way described at the top of the post when the watchdog is not included. But when including the watchdog, it bites after 30 seconds when the dog only should have bit after 8 minutes. I see this because data is being sent about every 25-30 seconds to the server. At first, I thought I had not activated the watchdog in the right way, so I wrote another program to test it:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;WDTZero.h&gt; #include &lt;RTCZero.h&gt; WDTZero MyWatchDoggy; RTCZero rtc; void set_RTC() { rtc.begin(); rtc.setYear(0); rtc.setMonth(0); rtc.setDay(0); rtc.setHours(0); rtc.setMinutes(0); rtc.setSeconds(0); } void shutdown() { Serial.println(&quot;Shutting down&quot;); } void setup() { Serial.begin(9600); while (!Serial) { } Serial.println(&quot;Starting up Arduino&quot;); MyWatchDoggy.attachShutdown(shutdown); MyWatchDoggy.setup(WDT_SOFTCYCLE8M); set_RTC(); } void loop() { Serial.print(rtc.getMinutes()); Serial.print(&quot;/&quot;); Serial.print(rtc.getSeconds()); Serial.println(&quot;&quot;); delay(1000); } </code></pre> <p>But in this program the watchdog bites after about 8 minutes as it should.</p> <p>I have not included the code for the functions described in the first code since I know they work without the watchdog and the code itself is very long. But if you think the problem could be caused by these functions for some reason, I will edit the post and include all the function codes.</p>
<p>In the WDTZero library the long watchdog times are achieved by restarting the watchdog timer in watchdog interrupt until the required time is reached.</p> <p>This doesn't work if the MCU sleeps.</p>
92250
|spi|display|tft|
TFT display shows black stripes
2023-02-11T16:24:26.070
<p>I'm new to the field: I'm trying to drive a TFT ST7735S display (this is the model I'm currently using: <a href="https://www.amazon.it/dp/B078JBBPXK/ref=pe_24968671_487022601_TE_SCE_dp_1" rel="nofollow noreferrer">https://www.amazon.it/dp/B078JBBPXK/ref=pe_24968671_487022601_TE_SCE_dp_1</a>) with an Arduino Mega following this video (<a href="https://www.youtube.com/watch?v=iPeukOK6stk&amp;ab_channel=Artigiano2.0-AlessioRomanelli" rel="nofollow noreferrer">https://www.youtube.com/watch?v=iPeukOK6stk&amp;ab_channel=Artigiano2.0-AlessioRomanelli</a>). Once the hardware is set up and the code is written, when I run the example script &quot;graphictest&quot; of the Adafruit library for st7735 and st7789, the display shows stripes on the background as shown in the picture below:</p> <p><a href="https://i.stack.imgur.com/KZFIm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KZFIm.jpg" alt="enter image description here" /></a> (Note that the strange effect is not camera's fault)</p> <p>Reading online I thought that the problem could be the fact that the display is powered with 5V instead of 3.3V, but I've also tried powering it with 3.3V (Arduino Mega 3.3V) with little to no changes. I've changed the <code>tft.initR(INITR_BLACKTAB);</code> to <code>tft.initR(INITR_GREENTAB);</code> too, as suggested by a user i this thread (<a href="https://forum.arduino.cc/t/bugged-1-8-inch-tft-diplay/1012166/5" rel="nofollow noreferrer">https://forum.arduino.cc/t/bugged-1-8-inch-tft-diplay/1012166/5</a>) and i've also tried powering the display with 5V but using 4.7k resistors in series to reduce the voltage as suggested in the same post, but it still doesn't work.</p> <p>Moreover the strange effect that the image shows does only appear, if I use a 5V supply, just when the program executes the <code>void setup()</code> function, then becomes sharp (this does not happen if I power the display using the Arduino Mega 3.3V output supply: in fact in this case the stripes are still present even when entering the <code>void loop()</code> function)</p> <p>As I said before, the program and the hardware setup arethe same as the video I was talking about. One thing I noticed is that, when I press the reset button on the Arduino Mega, an instant before the program is reloaded, the stripes disappear leaving the image as sharp as it should have been, without any strange background effect. Does anyone have any idea on how to solve this issue?</p> <p>Thank you in advance for any eventual answer!</p> <p><strong>EDIT</strong>:</p> <p>This is the picture of the modified verison of the connections, running the graphictest program with the suggested code:</p> <pre><code>#else // For the breakout board, you can use any 2 or 3 pins. // These pins will also work for the 1.8&quot; TFT shield. #define TFT_CS 10 //#define TFT_RST 9 // Or set to -1 and connect to Arduino RESET pin #define TFT_RST 8 // Or set to -1 and connect to Arduino RESET pin #define TFT_DC 9 #endif </code></pre> <p>// OPTION 2 lets you interface the display using ANY TWO or THREE PINS, // tradeoff being that performance is not as fast as hardware SPI above.</p> <pre><code>#define TFT_MOSI 11 // Data out #define TFT_SCLK 13 // Clock out // For ST7735-based displays, we will use this call Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST); </code></pre> <p><a href="https://i.stack.imgur.com/ESFzz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ESFzz.jpg" alt="enter image description here" /></a></p> <p>Hopefully every connection is visible</p>
<p>I had the exact same issue, and tested the things here but it did not help. Then I pressed the reset button on my UNO with the same result as Luke__ had (the screen looked nice as long as I pressed the reset). After doing that a few times the display started to work as it should.</p> <p>Strange, but resolved my issue.</p>
92259
|arduino-uno|esp8266|
How can I connect 2 Arduinos using ESP8266 transiver: ESP01
2023-02-12T15:29:41.760
<p>I have: 2 arduinos UNO, 2 ESP01 transivers. But if that's not enough, I'm ready to buy something else I need to use one of Arduinos as a wifi hot spot, and the second as a modem. They should just be connected to each other :) P.S. This is for my school project! Subsequently, I will put some obstacles between the Arduinos to see how much the signal strength degrades.</p>
<p>Here is the ESP8266 WiFi library:<br /> <a href="https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi</a></p> <p>In there You'll find an example for a WiFi access point:<br /> <a href="https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino</a></p> <p>And an example for WiFi client:<br /> <a href="https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino</a></p> <p>That should provide enough information for you to build your project.</p> <p>To get the signal strength without connecting, you can use WiFiScan:<br /> <a href="https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino</a></p>
92279
|input|reset|programmer|arduinoisp|
How to use reset pin as I/O pin with ATtiny44
2023-02-15T06:32:53.437
<p>I am using the Arduino IDE as an ISP programmer to program my ATtiny44 IC. Unfortunately, I ran out of pins, so I want to use the reset pin as I/O. I read several articles online that says it is possible and even the datasheet says so.</p> <p><a href="https://i.stack.imgur.com/J00bm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J00bm.png" alt="enter image description here" /></a></p> <p>I have a high voltage programmer as well. I wrote the code in the Arduino IDE and then used its hex file to program it using the high voltage programmer (TNM PROGRAMMER).</p> <p><a href="https://i.stack.imgur.com/Pmwkt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pmwkt.png" alt="enter image description here" /></a></p> <p>After I program, the IC stops working.</p> <p>////////////////////////////////////EDIT/////////////////////////////////////</p> <pre class="lang-cpp prettyprint-override"><code>const int led = 0; const int reset_led = 11; //physical pin 4 on attiny // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(led, OUTPUT); pinMode(reset_led, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(reset_led, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite (led, HIGH); delay(1000); // wait for a second digitalWrite(reset_led, LOW); // turn the LED off by making the voltage LOW digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>New fuse bit setup:</p> <p><a href="https://i.stack.imgur.com/Ha3YN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ha3YN.png" alt="enter image description here" /></a></p> <p>////////////////////////EDIT 2 /////////////////////////////////////////</p> <p><a href="https://i.stack.imgur.com/wIycI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wIycI.png" alt="enter image description here" /></a></p> <p>Now, the led on reset has turned off completely while the another still blinks. Powering my attiny44 with 5v.Code is same as before</p> <p>////////////////////////////////EDIT 3////////////////////////////////////</p> <pre><code>#include &lt;avr/io.h&gt; const int led = 0; #define ledd PB3 // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(led, OUTPUT); DDRB |= (uint8_t)(1&lt;&lt;PB3); pinMode (ledd, OUTPUT); } // the loop function runs over and over again forever void loop() { PORTB |= (uint8_t)(1&lt;&lt; PB3); digitalWrite (led, HIGH); digitalWrite (ledd, HIGH); delay(1000); // wait for a second PORTB &amp;= ~((uint8_t)(1 &lt;&lt; PB3)); // set PB3 to &quot;low&quot; digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>This code worked miraculously for me, Thanks to @thebusybee.</p> <p>/////////////////////////////EDIT 3/////////////////////////////////////////</p> <p>The PB3 pin is pin11 in arduino.</p> <p><a href="https://i.stack.imgur.com/jIsVa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jIsVa.png" alt="enter image description here" /></a></p>
<p>The <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/doc8006.pdf" rel="nofollow noreferrer">data sheet</a> gives insights:</p> <p>Chapter 1.1.4 states:</p> <blockquote> <p>The reset pin can also be used as a (weak) I/O pin.</p> </blockquote> <p>&quot;<em>Weak</em>&quot; means here, that the output function cannot deliver as much current as the other outputs, according to figures 21-24 to 21-27 beginning at page 198 roughly 2 to 3 mA. This is commonly not enough for LEDs, except you use a high-efficiency LED.</p> <p>And on page 66 is this relevant table (I cut the irrelevant column for PB2):</p> <blockquote> <p><strong>Table 10-8.</strong> Overriding Signals for Alternate Functions in PB[3:2]</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Signal Name</th> <th>PB3/RESET/dW/PCINT11</th> </tr> </thead> <tbody> <tr> <td>PUOE</td> <td>RSTDISBL<sup>(1)</sup> + DEBUGWIRE_ENABLE<sup>(2)</sup></td> </tr> <tr> <td>PUOV</td> <td>1</td> </tr> <tr> <td>DDOE</td> <td>RSTDISBL<sup>(1)</sup> + DEBUGWIRE_ENABLE<sup>(2)</sup></td> </tr> <tr> <td>DDOV</td> <td>DEBUGWIRE_ENABLE<sup>(2)</sup> • debugWire Transmit</td> </tr> <tr> <td>PVOE</td> <td>RSTDISBL<sup>(1)</sup> + DEBUGWIRE_ENABLE<sup>(2)</sup></td> </tr> <tr> <td>PVOV</td> <td>0</td> </tr> <tr> <td>PTOE</td> <td>0</td> </tr> <tr> <td>DIEOE</td> <td>RSTDISBL<sup>(1)</sup> + DEBUGWIRE_ENABLE<sup>(2)</sup> + PCINT11 • PCIE1</td> </tr> <tr> <td>DIEOV</td> <td>DEBUGWIRE_ENABLE<sup>(2)</sup> + (RSTDISBL<sup>(1)</sup> • PCINT11 • PCIE1)</td> </tr> <tr> <td>DI</td> <td>dW/PCINT11 Input</td> </tr> <tr> <td>AIO</td> <td></td> </tr> </tbody> </table> </div> <p>Note:</p> <ol> <li>RSTDISBL is 1 when the Fuse is “0” (Programmed).</li> <li>DebugWIRE is enabled when DWEN Fuse is programmed and Lock bits are unprogrammed.</li> </ol> </blockquote> <p>Since you have <code>DebugWIRE</code> enabled, this seems to be the cause. The alternate function <code>RESET</code> is still active.</p> <p>Please be aware that according to note 1 below table 19-4 on page 160:</p> <blockquote> <p>After programming the RSTDISBL fuse, high-voltage serial programming must be used to change fuses and allow further programming.</p> </blockquote> <p>This means that your circuit at PB3 needs to withstand the high voltage, and that the voltage source needs to provide enough current, which the circuit additionally draws at the high voltage.</p> <hr /> <p>Now to your code.</p> <p>You use the pin number &quot;0&quot; and hope to have PB3. Well, according to this shamelessly linked pinout this is not correct:</p> <p><a href="https://i.stack.imgur.com/VCjwB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VCjwB.jpg" alt="Arduino pinout ATtiny44" /></a></p> <p>Pin &quot;0&quot; is PA0.</p> <p>PB3 has no number assigned.</p> <p>Your next step could be to look up the sources of the Arduino library and check, if PB3 has a number assigned at all. I'm afraid this is not the case. If you're lucky and it has, use it. You will want to tell us about your finding then.</p> <p>You can directly access the data direction control register and the port register. Grab your data sheet and other documentation, read, and implement.</p> <p>This is untested:</p> <pre class="lang-c prettyprint-override"><code>// in setup(): DDRB |= (uint8_t)(1U &lt;&lt; 3); // in loop(): PORTB |= (uint8_t)(1U &lt;&lt; 3); // set PB3 to &quot;high&quot; PORTB &amp;= ~((uint8_t)(1U &lt;&lt; 3)); // set PB3 to &quot;low&quot; </code></pre>
92287
|arduino-uno|button|wires|
Button Matrix / Wiring Schematics
2023-02-16T00:53:22.487
<p>I am just beginning my journey into the Arduino world - plenty of development experience, but basically nothing with electronics outside of building computers.</p> <p>The question I have involves wiring schematics - specifically for a button matrix, but it does apply more broadly. Using this diagram and Fritzing mapping, I see numerous buttons connected to each other - presumably via soldering:</p> <p><a href="https://i.stack.imgur.com/9cwHV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9cwHV.png" alt="Diagram" /></a></p> <p><a href="https://i.stack.imgur.com/V25m3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V25m3.png" alt="Fritzing" /></a></p> <p>My question is, can you use wire nuts (or, more specifically multi-slot lever connectors) such as these to simplify the connection process?</p> <p><a href="https://i.stack.imgur.com/eJXYU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJXYU.jpg" alt="Levers" /></a></p> <p>I apologize in advance if this seems obvious, but I get lost trying to understand how to connect this stuff because I'm so new to it all.</p> <p>Thanks in advance!</p>
<p>Assuming that &quot;multi-slot lever connectors&quot; is shorting the inserted wires together I see no reason why you could not use them.</p> <p>If you are adverse to soldering consider using switches and cables commonly found in arcade machines instead.</p> <p>Previously crimped cables ...</p> <p><a href="https://i.stack.imgur.com/t8M6d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t8M6d.jpg" alt="enter image description here" /></a></p> <p>And arcade style micro switches ...</p> <p><a href="https://i.stack.imgur.com/PydB4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PydB4.jpg" alt="enter image description here" /></a></p> <p>Can be combined / connected to form the switch matrix your designed above.</p>
92300
|attiny|reset|
How to declare PB3 reset pin of ATtiny44 in program (using arduino IDE platform)
2023-02-17T07:21:55.410
<p>As follow-up of my <a href="https://arduino.stackexchange.com/questions/92279/how-to-use-reset-pin-as-i-o-pin-with-attiny44/92290?noredirect=1#comment212771_92290">former question</a>:</p> <p>Hi, I want to know how I can access PB3 reset pin of ATtiny44 IC. I ran out of pins so I am using it as I/O pin, but I am unable to declare it in the code.</p> <p><a href="https://i.stack.imgur.com/awKYr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awKYr.jpg" alt="enter image description here" /></a></p> <p>This picture above says that PB3 is pin 11. But if I declare it as pin 11, the reset pin does not function at all.</p> <pre class="lang-cpp prettyprint-override"><code>// in setup(): DDRB |= (uint8_t)(1U &lt;&lt; 3); // in loop(): PORTB |= (uint8_t)(1U &lt;&lt; 3); // set PB3 to &quot;high&quot; PORTB &amp;= ~((uint8_t)(1U &lt;&lt; 3)); // set PB3 to &quot;low&quot; </code></pre> <p>This code works with only direct declaration.</p> <p>In my code I just need to add pin number to the command like <code>#define CSN 2</code>.</p> <p><a href="https://i.stack.imgur.com/e9Tpb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9Tpb.png" alt="PB3 of ATtiny" /></a></p> <hr /> <p><strong>EDIT</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;avr/io.h&gt; const int led = 0; #define led1 11 // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(led, OUTPUT); pinMode(led1, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(led, HIGH); digitalWrite(led1, HIGH); delay(1000); // wait for a second digitalWrite(led1, LOW); digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>This is the code that does not work (led1 is reset pin as GPIO). Even if I change the led1 declaration to PB3 of PCINT11, it still does not work.</p> <p><a href="https://i.stack.imgur.com/qaEN3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qaEN3.png" alt="Fusebits config" /></a></p>
<p>i resolved my issue by installing spenceKonde ATtinyCore library, The RESET pin is pin 11 of attiny44 IC and in order to access it inside the code we need attinyCore library not Damellis( damellis does not have RESET programming access).</p>
92304
|arduino-ide|time|arduino-nano-ble|
Arduino Nano 33 BLE getting the current time using RTC
2023-02-17T18:37:15.287
<p>I have a an <a href="https://docs.arduino.cc/hardware/nano-33-ble" rel="nofollow noreferrer">arduino NANO 33 BLE</a> and I'm trying to get the current time and date. Based on the documentation, the arduino has nRF52840 microcontroller which comes with a <a href="https://nsscprodmedia.blob.core.windows.net/prod/software-and-other-downloads/product-briefs/nrf52840-soc-v3.0.pdf" rel="nofollow noreferrer">24 RTC timer</a> It is listed in the <a href="https://infocenter.nordicsemi.com/index.jsp?topic=%2Fstruct_nrf52%2Fstruct%2Fnrf52840.html" rel="nofollow noreferrer">nordic documentation</a> as well. However, I'm not sure exactly how to use it to get the current time; Based on the <a href="https://os.mbed.com/docs/mbed-os/v6.15/apis/time.html" rel="nofollow noreferrer">MbedOS documentation for Time</a> I wrote out the code to print out the current time and date in conjunction with reading the data:</p> <pre><code>#include &quot;mbed.h&quot; #include &lt;Time.h&gt; #include &lt;RTClib.h&gt; time_t rawtime; struct tm *info; void setup() { Serial.begin(9600); } //resistor val = 100K void loop() { rawtime = time(NULL); time(&amp;rawtime); info = localtime(&amp;rawtime); int val = analogRead(A1); Serial.print(val); Serial.print('-'); Serial.print(asctime(info) ); delay(5); } </code></pre> <p>However it just prints out this:</p> <blockquote> <p>XX-Thu Jan 1 00:08:30 1970</p> </blockquote> <p>Where the XX is the correct sensor data. Why is the time not the current time but the beginning unix epoch ? This code was run in the Desktop Arduino IDE in Win10</p>
<p>I was going to write something more elaborate, but in short the RTC in the NRF52840 is not a &quot;clock&quot; so much as an asynchronous timer/counter. As in, you can run it from a clock source that isn't related to the system clock that times your code and it may (or may not) continue to count when you're in a sleep mode. So, you may be able to use this async. timer/counter as a building block in constructing what amounts to an approximation of a real-time clock (like a DS3231). That you might use it that way isn't assumed by Nordic, or mbed, or Arduino, or libc/<code>time.h</code>, and <code>RTCLib.h</code> concerns itself with accessing specific models external realtime clock chips with no direct connection to <code>time.h</code>. So there's nothing to support your specific use case in each of these things.</p> <p>So you can try to build a real-time clock functionality out of it. But if you're like most Arduino users you're probably better off getting a DS3231 or something like it. You will probably end up with more accurate time keeping and battery backup, etc than you would if you build this functionality yourself out of the NRF52's counter.</p> <p>If you have a need or strong desire to use <code>&lt;time.h&gt;</code>, that can usually be done by completing its implementation in some implementation specific documented way. Basically you'd retrieve the time fields out of something like the DS3231 an then use that to set what amounts to a <code>time_t</code> variable that backs <code>time()</code> and then to call regularly call some kind of time advance function from an interrupt routine based on the square wave output from the DS3231 (or whatever). If you really want to make use of the async. counter yourself, all of that applies there as well.</p>