Problem with 'if'

Moderators: adafruit_support_bill, adafruit

Forum rules
Talk about Adafruit Raspberry Pi® accessories! Please do not ask for Linux support, this is for Adafruit products only! For Raspberry Pi help please visit: http://www.raspberrypi.org/phpBB3/
Locked
User avatar
GilbertGagne
 
Posts: 13
Joined: Mon Nov 09, 2020 12:53 pm

Problem with 'if'

Post by GilbertGagne »

I am a newbie user of MicroPython with Thonny on a Raspberry Pi Pico board.
My program is reading a sensor in I2C that puts out 2 bytes (msb & lsb) of a 16 bit number in 2's complement.
The 16 bit number is scaled by dividing it by 4096.
This is my code, line 58 is the (else:) line:

Code: Select all

   if msb > 0x7F:			#if bit7=1 (negative): do 2's complement
        data16 = ~((msb << 8) | lsb)	#1st do 1's complement 
        data16 +1=			#then add 1
    else:
        data16 = (msb << 8) | lsb
    data16  /= 4096			#finally, div result by 4096

Code: Select all

>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 58
SyntaxError: invalid syntax
>>> 
This is my first use of an 'if' statement. My understanding is obviously missing something.
Last edited by adafruit_support_carter on Thu Jun 01, 2023 1:00 pm, edited 1 time in total.
Reason: added [code] tags

User avatar
edgjr
 
Posts: 143
Joined: Mon Jan 16, 2012 6:18 pm

Re: Problem with 'if'

Post by edgjr »

First, it's easier to read if you use the "code" tags and paste in the code as it appears in the editor (including spaces).

Just as a guess, you have a typo in the line before the "else:"

Code: Select all

    data16 +1= #then add 1
else:
Not valid code in any language that I know... :D

User avatar
adafruit_support_carter
 
Posts: 29056
Joined: Tue Nov 29, 2016 2:45 pm

Re: Problem with 'if'

Post by adafruit_support_carter »

Agree it's probably the typo on the line *before*.

Also, just to mention, the Python struct module is useful for turning multiple bytes into values.
https://docs.python.org/3/library/struct.html

User avatar
blakebr
 
Posts: 942
Joined: Tue Apr 17, 2012 6:23 pm

Re: Problem with 'if'

Post by blakebr »

Your code should read:

Code: Select all

   if msb > 0x7F:			#if bit7=1 (negative): do 2's complement
        data16 = ~((msb << 8) | lsb)	#1st do 1's complement 
        data16 += 1				#then add 1
    else:
        data16 = (msb << 8) | lsb
    data16  /= 4096			#finally, div result by 4096
Good luck.

Bruce

User avatar
GilbertGagne
 
Posts: 13
Joined: Mon Nov 09, 2020 12:53 pm

Re: Problem with 'if'

Post by GilbertGagne »

It was a typo; after correction - no problem.

Thank you all for looking.

Locked
Forum rules
Talk about Adafruit Raspberry Pi® accessories! Please do not ask for Linux support, this is for Adafruit products only! For Raspberry Pi help please visit: http://www.raspberrypi.org/phpBB3/

Return to “Adafruit Raspberry Pi® accessories”